Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim string from the end of a string in .NET - why is this missing?

Tags:

string

c#

.net

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...)

like image 514
Brady Moritz Avatar asked Aug 24 '11 05:08

Brady Moritz


People also ask

How do you trim the ends of a string?

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.

What is trim end in C#?

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)

How do you trim the last 3 characters of a string?

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.


1 Answers

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");

like image 69
Yahia Avatar answered Sep 20 '22 08:09

Yahia