Advertisement
Advertisement


Trim last character from a string


Question

I have a string say

"Hello! world!" 

I want to do a trim or a remove to take out the ! off world but not off Hello.

2010/08/26
1
158
8/26/2010 8:36:14 AM

Accepted Answer

"Hello! world!".TrimEnd('!');

read more

EDIT:

What I've noticed in this type of questions that quite everyone suggest to remove the last char of given string. But this does not fulfill the definition of Trim method.

Trim - Removes all occurrences of white space characters from the beginning and end of this instance.

MSDN-Trim

Under this definition removing only last character from string is bad solution.

So if we want to "Trim last character from string" we should do something like this

Example as extension method:

public static class MyExtensions
{
  public static string TrimLastCharacter(this String str)
  {
     if(String.IsNullOrEmpty(str)){
        return str;
     } else {
        return str.TrimEnd(str[str.Length - 1]);
     }
  }
}

Note if you want to remove all characters of the same value i.e(!!!!)the method above removes all existences of '!' from the end of the string, but if you want to remove only the last character you should use this :

else { return str.Remove(str.Length - 1); }
300
9/15/2017 9:20:37 PM

String withoutLast = yourString.Substring(0,(yourString.Length - 1));
2017/06/30

if (yourString.Length > 1)
    withoutLast = yourString.Substring(0, yourString.Length - 1);

or

if (yourString.Length > 1)
    withoutLast = yourString.TrimEnd().Substring(0, yourString.Length - 1);

...in case you want to remove a non-whitespace character from the end.

2013/07/15

        string s1 = "Hello! world!";
        string s2 = s1.Trim('!');
2010/08/26

Try this:

return( (str).Remove(str.Length-1) );
2017/08/20

string helloOriginal = "Hello! World!";
string newString = helloOriginal.Substring(0,helloOriginal.LastIndexOf('!'));
2010/08/26

Source: https://stackoverflow.com/questions/3573284
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]