- Home /
string.TrimEnd() not working as expected
string str = GamesStatistics;
strng trimmedStr = str.TrimEnd("Statistics".ToCharArray());
//trimmedStr = Game
plese help, how can I avoid this ? I expect it to trim only the statistics word but it trimmes the previous letter also
Comment
Best Answer
Answer by Landern · Dec 02, 2014 at 05:13 PM
In your case, the letters "S", "t", "a", "i", "s" and "c" will be removed from the end of a string if they exist.
You may want to use:
str = str.Substring(0, str.LastIndexOf("Staticstics"));
In the case above, using Substring and LastIndexOf does the following.
LastIndexOf will get the last occurance of a string or character by index in the string(a string is a character array).
Substring begins hacking from the beginning(index 0) of the string all the way until the index of "Staticstics", so it's lopped off.