C# TrimStart with string parameter

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

    If you did want one that didn't use the built in trim functions for whatever reasons, assuming you want an input string to use for trimming such as " ~!" to essentially be the same as the built in TrimStart with [' ', '~', '!']

    public static String TrimStart(this string inp, string chars)
    {
        while(chars.Contains(inp[0]))
        {
            inp = inp.Substring(1);
        }
    
        return inp;
    }
    
    public static String TrimEnd(this string inp, string chars)
    {
        while (chars.Contains(inp[inp.Length-1]))
        {
            inp = inp.Substring(0, inp.Length-1);
        }
    
        return inp;
    }
    

提交回复
热议问题