How to extend C# built-in types, like String?

前端 未结 5 1824
别那么骄傲
别那么骄傲 2020-11-28 23:13

Greetings everyone... I need to Trim a String. But I want to remove all the repeated blank spaces within the String itself, not only at the end or

5条回答
  •  被撕碎了的回忆
    2020-11-28 23:31

    Since you cannot extend string.Trim(). You could make an Extension method as described here that trims and reduces whitespace.

    namespace CustomExtensions
    {
        //Extension methods must be defined in a static class
        public static class StringExtension
        {
            // This is the extension method.
            // The first parameter takes the "this" modifier
            // and specifies the type for which the method is defined.
            public static string TrimAndReduce(this string str)
            {
                return ConvertWhitespacesToSingleSpaces(str).Trim();
            }
    
            public static string ConvertWhitespacesToSingleSpaces(this string value)
            {
                return Regex.Replace(value, @"\s+", " ");
            }
        }
    }
    

    You can use it like so

    using CustomExtensions;
    
    string text = "  I'm    wearing the   cheese.  It isn't wearing me!   ";
    text = text.TrimAndReduce();
    

    Gives you

    text = "I'm wearing the cheese. It isn't wearing me!";
    

提交回复
热议问题