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

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

    TrimEnd() (and the other trim methods) accept characters to be trimmed, but not strings. If you really want a version that can trim whole strings then you could create an extension method. For example...

    public static string TrimEnd(this string input, string suffixToRemove, StringComparison comparisonType = StringComparison.CurrentCulture)
    {
        if (suffixToRemove != null && input.EndsWith(suffixToRemove, comparisonType)) 
        {
            return input.Substring(0, input.Length - suffixToRemove.Length);
        }
    
        return input;
    }
    

    This can then be called just like the built in methods.

    0 讨论(0)
提交回复
热议问题