I need this all the time and am constantly frustrated that the Trim(), TrimStart() and TrimEnd() functions don't take strings as inputs. You call EndsWith() on a string, and find out if it ends with another string, but then if you want to remove it from the end, you have to do substring hacks to do it (or call Remove() and pray it is the only instance...)
Why is this basic function is missing in .NET? And second, any recommendations for a simple way to implement this (preferably not the regular expression route...)
String. TrimEnd(Char[]) method is used to remove all specified characters from trailing edge of the current string. String. TrimEnd() does not modify the original string but returns a new String instance with the trailing white-space/specified characters removed from the given string value.
TrimEnd(Char[]) Removes all the trailing occurrences of a set of characters specified in an array from the current string. TrimEnd() Removes all the trailing white-space characters from the current string. TrimEnd(Char)
The substring starts at a specified character position and has a specified length. You can also using String. Remove(Int32) method to remove the last three characters by passing start index as length - 3, it will remove from this point to end of string.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With