Trim last character from a string

后端 未结 14 1411
谎友^
谎友^ 2020-11-29 23:59

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.

14条回答
  •  甜味超标
    2020-11-30 00:56

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

提交回复
热议问题