I\'m looking for String extension methods for TrimStart()
and TrimEnd()
that accept a string parameter.
I could build one myself but I\'m alw
To trim all occurrences of the (exactly matching) string, you can use something like the following:
public static string TrimStart(this string target, string trimString)
{
if (string.IsNullOrEmpty(trimString)) return target;
string result = target;
while (result.StartsWith(trimString))
{
result = result.Substring(trimString.Length);
}
return result;
}
public static string TrimEnd(this string target, string trimString)
{
if (string.IsNullOrEmpty(trimString)) return target;
string result = target;
while (result.EndsWith(trimString))
{
result = result.Substring(0, result.Length - trimString.Length);
}
return result;
}
To trim any of the characters in trimChars from the start/end of target (e.g. "foobar'@"@';".TrimEnd(";@'")
will return "foobar"
) you can use the following:
public static string TrimStart(this string target, string trimChars)
{
return target.TrimStart(trimChars.ToCharArray());
}
public static string TrimEnd(this string target, string trimChars)
{
return target.TrimEnd(trimChars.ToCharArray());
}