C# TrimStart with string parameter

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

    Function to trim start/end of a string with a string parameter, but only once (no looping, this single case is more popular, loop can be added with an extra param to trigger it) :

    public static class BasicStringExtensions
    {
        public static string TrimStartString(this string str, string trimValue)
        {
            if (str.StartsWith(trimValue))
                return str.TrimStart(trimValue.ToCharArray());
            //otherwise don't modify
            return str;
        }
        public static string TrimEndString(this string str, string trimValue)
        {
            if (str.EndsWith(trimValue))
                return str.TrimEnd(trimValue.ToCharArray());
            //otherwise don't modify
            return str;
        }
    }
    

    As mentioned before, if you want to implement the "while loop" approach, be sure to check for empty string otherwise it can loop forever.

提交回复
热议问题