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

前端 未结 13 1371
夕颜
夕颜 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:23

    I like my TrimEnd to remove all the instances of the string at the end and not just the last one.

    public static string TrimEnd(this string str, string trimStr)
    {
        if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(trimStr)) return str;
    
        while(str.EndsWith(trimStr))
        {
            str = str.Remove(str.LastIndexOf(trimStr));
        }
        return str;
    }
    

提交回复
热议问题