C# TrimStart with string parameter

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

    To match entire string and not allocate multiple substrings, you should use the following:

        public static string TrimStart(this string source, string value, StringComparison comparisonType)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
    
            int valueLength = value.Length;
            int startIndex = 0;
            while (source.IndexOf(value, startIndex, comparisonType) == startIndex)
            {
                startIndex += valueLength;
            }
    
            return source.Substring(startIndex);
        }
    
        public static string TrimEnd(this string source, string value, StringComparison comparisonType)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
    
            int sourceLength = source.Length;
            int valueLength = value.Length;
            int count = sourceLength;
            while (source.LastIndexOf(value, count, comparisonType) == count - valueLength)
            {
                count -= valueLength;
            }
    
            return source.Substring(0, count);
        }
    

提交回复
热议问题