97

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 at the start of it. I could do it with a method like:

public static string ConvertWhitespacesToSingleSpaces(string value)
{
    value = Regex.Replace(value, @"\s+", " ");
}

Which I got from here. But I want this piece of code to be called within the String.Trim() itself, so I think I need to extend or overload or override the Trim method... Is there a way to do that?

starball
  • 20,030
  • 7
  • 43
  • 238
Girardi
  • 2,734
  • 3
  • 35
  • 50

5 Answers5

179

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!";
d219
  • 2,707
  • 5
  • 31
  • 36
JoeyRobichaud
  • 2,689
  • 1
  • 15
  • 11
  • Does file needs a special name? Or where do you save this? Can it be putted into an Util class or something like that? – testing Sep 17 '14 at 12:54
  • 1
    @testing You can put them anywhere as long as they're referenced into your project. If you put them in a specific namespace, just bring them in with a 'using' statement like any other class. – Twicetimes Oct 07 '14 at 10:07
  • why didn't you return the regex right from the TrimAndReduce function? it would have made your answer much simpler to read. Unless you use your answer so much that you need to call that elsewhere LOL – quemeful Feb 07 '17 at 16:06
24

Is it possible? Yes, but only with an extension method

The class System.String is sealed so you can't use overriding or inheritance.

public static class MyStringExtensions
{
  public static string ConvertWhitespacesToSingleSpaces(this string value)
  {
    return Regex.Replace(value, @"\s+", " ");
  }
}

// usage: 
string s = "test   !";
s = s.ConvertWhitespacesToSingleSpaces();
H H
  • 263,252
  • 30
  • 330
  • 514
12

There's a yes and a no to your question.

Yes, you can extend existing types by using extension methods. Extension methods, naturally, can only access the public interface of the type.

public static string ConvertWhitespacesToSingleSpaces(this string value) {...}

// some time later...
"hello world".ConvertWhitespacesToSingleSpaces()

No, you cannot call this method Trim(). Extension methods do not participate in overloading. I think a compiler should even give you a error message detailing this.

Extension methods are only visible if the namespace containing the type that defines the method is using'ed.

d219
  • 2,707
  • 5
  • 31
  • 36
Arne
  • 750
  • 5
  • 10
7

Extension methods!

public static class MyExtensions
{
    public static string ConvertWhitespacesToSingleSpaces(this string value)
    {
        return Regex.Replace(value, @"\s+", " ");
    }
}
Corey Sunwold
  • 10,194
  • 6
  • 51
  • 55
2

Besides using extension methods -- likely a good candidate here -- it is also possible to "wrap" an object (e.g. "object composition"). As long as the wrapped form contains no more information than the thing being wrapped then the wrapped item may be cleanly passed through implicit or explicit conversions with no loss of information: just a change of type/interface.

Happy coding.