Trim last character from a string

后端 未结 14 1374
谎友^
谎友^ 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); }
    
    0 讨论(0)
  • 2020-11-30 00:57

    Slightly modified version of @Damian Leszczyński - Vash that will make sure that only a specific character will be removed.

    public static class StringExtensions
    {
        public static string TrimLastCharacter(this string str, char character)
        {
            if (string.IsNullOrEmpty(str) || str[str.Length - 1] != character)
            {
                return str;
            }
            return str.Substring(0, str.Length - 1);
        }
    }
    
    0 讨论(0)
提交回复
热议问题