C# TrimStart with string parameter

后端 未结 9 829
轻奢々
轻奢々 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:38

    To trim all occurrences of the (exactly matching) string, you can use something like the following:

    TrimStart

    public static string TrimStart(this string target, string trimString)
    {
        if (string.IsNullOrEmpty(trimString)) return target;
    
        string result = target;
        while (result.StartsWith(trimString))
        {
            result = result.Substring(trimString.Length);
        }
    
        return result;
    }
    

    TrimEnd

    public static string TrimEnd(this string target, string trimString)
    {
        if (string.IsNullOrEmpty(trimString)) return target;
    
        string result = target;
        while (result.EndsWith(trimString))
        {
            result = result.Substring(0, result.Length - trimString.Length);
        }
    
        return result;
    }
    

    To trim any of the characters in trimChars from the start/end of target (e.g. "foobar'@"@';".TrimEnd(";@'") will return "foobar") you can use the following:

    TrimStart

    public static string TrimStart(this string target, string trimChars)
    {
        return target.TrimStart(trimChars.ToCharArray());
    }
    

    TrimEnd

    public static string TrimEnd(this string target, string trimChars)
    {
        return target.TrimEnd(trimChars.ToCharArray());
    }
    

提交回复
热议问题