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

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

    Here's the extension method I came up with (heavy inspiration taken from existing answers to this question) to complement the existing TrimEnd method; it takes an optional bool allowing for only removing one trailing instance of the string instead of all trailing instances.

    /// 
    /// Removes trailing occurrence(s) of a given string from the current System.String object.
    /// 
    /// A string to remove from the end of the current System.String object.
    /// If true, removes all trailing occurrences of the given suffix; otherwise, just removes the outermost one.
    /// The string that remains after removal of suffix occurrence(s) of the string in the trimSuffix parameter.
    public static string TrimEnd(this string input, string trimSuffix, bool removeAll = true) {
        while (input != null && trimSuffix != null && input.EndsWith(trimSuffix)) {
            input = input.Substring(0, input.Length - trimSuffix.Length);
    
            if (!removeAll) {
                return input;
            }
        }
    
        return input;
    }
    

提交回复
热议问题