Ehbit ninja's blog

Our IT ninja's blog about their professional experiences with IT technologies

Replace multiple spaces by a single space

We had a problem with multiple spaces in the messages received from another party.
I’ll provide you an answer to handle this problem in XSLT as well as for C#.

I’ll start by explaining it for XSLT.
In this case it is really simple, there exists an XSLT function to do this for u. Simply make a call to the function ‘normalize-space()’, and that’s it!
normalize-space will remove all leading and trailing spaces to the string you pass to it. And above this, it will also replace all multiple spaces with a single space. It is that easy.

    for example:
          <value-of select=normalize-space(RootNode/SubNode/AnotherSubNode) />

In C# there is no build-in solution for this problem, at least none that I’m aware of.
I solved this by writing a simple function, as follows:

        public String RemoveMultipleSpaces(String phrase)
            phrase = phrase.Trim();
            phrase = System.Text.RegularExpressions.Regex.Replace(phrase, “\s+”, ” “);

            return phrase;

This functions exists of 2 steps. First of all I’ll remove all leading and trailing spaces in the string.
Then I replace all remaining multiple spaces by a single space. To do this I use the Regex.Replace(String, String, String) function. The first parameter is just the String that needs to be changed. The second parameter represents a regalur expression of the  pattern that needs to be replaced, in this case its mulitple spaces. And finally, the last parameter is the single space that will replace all matching substrings inside the original string.