Trim string from the end of a string in .NET - why is this missing?
EDIT - wrapped up into a handy extension method:
public static string TrimEnd(this string source, string value)
{
if (!source.EndsWith(value))
return source;
return source.Remove(source.LastIndexOf(value));
}
so you can just do s = s.TrimEnd("DEF");
TrimEnd()
(and the other trim methods) accept characters to be trimmed, but not strings. If you really want a version that can trim whole strings then you could create an extension method. For example...
public static string TrimEnd(this string input, string suffixToRemove, StringComparison comparisonType = StringComparison.CurrentCulture)
{
if (suffixToRemove != null && input.EndsWith(suffixToRemove, comparisonType))
{
return input.Substring(0, input.Length - suffixToRemove.Length);
}
return input;
}
This can then be called just like the built in methods.
I knocked up this quick extension method.
Not positive it works (I can't test it right now), but the theory is sound.
public static string RemoveLast(this string source, string value)
{
int index = source.LastIndexOf(value);
return index != -1 ? source.Remove(index, value.Length) : source;
}
Using Daniel's code and wrapping it in a while rather than a straight if
gives functionality more akin to the Microsoft Trim
function:
public static string TrimEnd(this string input, string suffixToRemove)
{
while (input != null && suffixToRemove != null && input.EndsWith(suffixToRemove))
{
input = input.Substring(0, input.Length - suffixToRemove.Length);
}
return input;
}