SubstringBefore and SubstringAfter for .NET
C# implementation of the functions available in XPath for getting either the string before or after a given part:
static class StringEx
{
public static string SubstringAfter(this string source, string value)
{
if (string.IsNullOrEmpty(source) || string.IsNullOrEmpty(value))
return source;
int index = source.IndexOf(value, StringComparison.Ordinal);
return (index >= 0)
? source.Substring(index + value.Length)
: source;
}
public static string SubstringBefore(this string source, string value)
{
if (string.IsNullOrEmpty(source) || string.IsNullOrEmpty(value))
return source;
int index = source.IndexOf(value, StringComparison.Ordinal);
return (index >= 0)
? source.Substring(0, index)
: source;
}
}