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

前端 未结 13 1335
夕颜
夕颜 2020-12-13 12:08

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, an

13条回答
  •  [愿得一人]
    2020-12-13 12:37

    Trim(), TrimStart() and TrimEnd() are methods which replace all occurrences of the same character. That means you can only remove a series of blanks or a series of dots for example.

    You could use a regular expression replace in order to accomplish this:

    string s1 = "This is a sentence.TRIMTHIS";
    string s2 = System.Text.RegularExpressions.Regex.Replace(s1, @"TRIMTHIS$", "");
    

    You could wrap it in an extension method for convenience:

    public static string TrimStringEnd(this string text, string removeThis)
    {
        return System.Text.RegularExpressions.Regex.Replace(s1, removeThis, "");
    }
    

    And call it this way

    string s2 = (@"This is a sentence.TRIMTHIS").TrimStringEnd(@"TRIMTHIS");
    

提交回复
热议问题