C# TrimStart with string parameter

后端 未结 9 685
轻奢々
轻奢々 2021-02-04 23:00

I\'m looking for String extension methods for TrimStart() and TrimEnd() that accept a string parameter.

I could build one myself but I\'m alw

9条回答
  •  余生分开走
    2021-02-04 23:30

    I thought the question was trying to trim a specific string from the start of a larger string.

    For instance, if I had the string "hellohellogoodbyehello", if you tried to call TrimStart("hello") you would get back "goodbyehello".

    If that is the case, you could use code like the following:

    string TrimStart(string source, string toTrim)
    {
        string s = source;
        while (s.StartsWith(toTrim))
        {
            s = s.Substring(toTrim.Length - 1);
        }
        return s;
    }
    

    This wouldn't be super-efficient if you needed to do a lot of string-trimming, but if its just for a few cases, it is simple and gets the job done.

提交回复
热议问题