Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

My implementation:

string ReplaceAllSpaces(string input)
{
    StringBuilder builder = new StringBuilder();
    using(StringReader reader = new StringReader(input))
    {
        while(reader.Peek() != -1)
        {
            char c = (char)reader.Peek();
            if(char.IsWhiteSpace(c))
            {
                while(char.IsWhiteSpace(c)) 
                { 
                    reader.Read(); 
                    c = (char)reader.Peek();
                } 
                builder.Append("%20");
            }
            else builder.Append((char)reader.Read()); 
        }
    }
    return builder.ToString();
}

Input:

"My      Name Is  John"

Output:

"My%20Name%20Is%20John"

How could this be improved? Only ASCII characters are permitted.

share|improve this question
7  
Is there something you're trying to accomplish that input.Replace(" ", "%20"); won't? –  Comintern yesterday
7  
This replaces several consecutive spaces with a single %20. Is this the desired behaviour? Usually each space would be replaced by a single %20. –  mjolka yesterday
1  
@mjolka Yes. I'll add some more information to the question. –  Rezo Megrelidze yesterday
2  
Is there a problem with UrlEncode() ? Gets all non-roman characters, not just spaces. –  paul 11 hours ago
1  
Are you certain that it's only spaces you need to escape as percent-encoded characters? There are other characters besides spaces which need to be precent-encoded when used in a URL: en.wikipedia.org/wiki/… (If you need to escape these characters too, it's probably a good idea to use a library.) –  Ajedi32 10 hours ago

4 Answers 4

This one really fits well for a regular expression:

public static string ReplaceAllSpaces(string str) {
  return Regex.Replace(str, @"\s+","%20");
}

The expression \s+ consists of the pattern \s that matches a whitespace character (which is more that just spaces, as noted by @tinstaafl), and the quantifier + which means "at least once".

The pattern matches "one or more whitespace characters", so it will match each group of whitespace characters (for example the six spaces between My and Name in the example) and replace it with %20.

share|improve this answer
4  
This is what Regexes were made for. –  Mark 18 hours ago
    
The only correct answer in my opinion. No need to write lines of code for something which can be done in such a simple way. =) –  Abbas 11 hours ago
    
would you please explain for OP how this does exactly the same as his code but is much better? I always have to look up Regex if I need to use it, so does your code replace 5 spaces with one %20 or does it replace them with %20%20%20%20%20 –  Malachi 9 hours ago
2  
@Malachi: this is a very simple regex. It is composed of a pattern and a quantifier. the pattern is \s, or whitespaces (btw, this englobes much more that just spaces, as noted by @tinstaafl), and the quantifier is +, which is at least once. –  njzk2 9 hours ago
1  
@njzk2: Thanks for the suggested edit. I used most of it (just wanted to put it in my own words), and added an example from the data in the question. –  Guffa 9 hours ago

Since a string is basically a character array, I would do away with the stringreader and simply loop through the string itself:

    static string ReplaceAllSpaces(string input)
    {
        StringBuilder builder = new StringBuilder();
        bool continuousSpace = false;
        foreach (char c in input)
        {
            if (!continuousSpace && char.IsWhiteSpace(c))
            {
                builder.Append("%20");
                continuousSpace = true;
            }
            else if(!char.IsWhiteSpace(c))
            {
                builder.Append(c);
                continuousSpace = false;
            }
        }
        return builder.ToString();
    }

A side note: Whitespace includes a lot of other characters in the unicode set as well as the space.

White space characters are the following Unicode characters:

Members of the SpaceSeparator category, which includes the characters

SPACE (U+0020), OGHAM SPACE MARK (U+1680), MONGOLIAN VOWEL SEPARATOR (U+180E), EN QUAD (U+2000), EM QUAD (U+2001), EN SPACE (U+2002), EM SPACE (U+2003), THREE-PER-EM SPACE (U+2004), FOUR-PER-EM SPACE (U+2005), SIX-PER-EM SPACE (U+2006), FIGURE SPACE (U+2007), PUNCTUATION SPACE (U+2008), THIN SPACE (U+2009), HAIR SPACE (U+200A), NARROW NO-BREAK SPACE (U+202F), MEDIUM MATHEMATICAL SPACE (U+205F), and IDEOGRAPHIC SPACE (U+3000).

Members of the LineSeparator category, which consists solely of the LINE SEPARATOR character (U+2028).

Members of the ParagraphSeparator category, which consists solely of the PARAGRAPH SEPARATOR character (U+2029).

The characters CHARACTER TABULATION (U+0009), LINE FEED (U+000A), LINE TABULATION (U+000B), FORM FEED (U+000C), CARRIAGE RETURN (U+000D), NEXT LINE (U+0085), and NO-BREAK SPACE (U+00A0).

share|improve this answer
    
Let's ignore Unicode for now. –  Rezo Megrelidze 23 hours ago
6  
The whitespace category will still include those character codes that are considered ASCII(9,10,11,12,13,32, etc.) –  tinstaafl 23 hours ago

Is there anything wrong with this?

string replaceAllSpaces(string input)
{
    return input.Replace(@" ", @"%20");
}

Maybe add some input validation, if you need.

Since it is only one specific char we want to replace, there is no need to whip out a Regex, especially if you're not comfortable around those.
On the other side the Regex approach is better in terms of scalability, if you ever need to complicate the criteria for a replacement.

Also since only ASCII-chars are allowed, there is not problem with the dozens of other chars that are practically whitespace but not the whitespace, that are included in unicode. (See tinstaafl's answer).

share|improve this answer
1  
it is only one specific char we want to replace: false. The question is replacing tabs too... and other white-space characters. –  ANeves 14 hours ago
1  
Also, the question was clarified to demonstrate that the OP wishes to replace multiple consecutive whitespaces with a single %20 –  Doktor J 8 hours ago

Without regex

string ReplaceAllSpaces(string input)
{
    StringBuilder sb= new StringBuilder();
    var v = input.Split(new char[]{' '},StringSplitOptions.RemoveEmptyEntries)
    for(int i = 0; i < v.Length; i++)
      {
         if(i < v.Length - 1)
          sb.Append(v[i]+"%20");
         else
          sb.Append(v[i]);
      }
    return sb.ToString();
}
share|improve this answer
3  
Won't compile. Also you are creating a bunch of String's which isn't neccessary. Hint: builder!=sb s!=input –  Heslacher 13 hours ago
    
I know it isn't "necessary", mine was just to show one of the possible alternatives of accomplishing the task without regex. The OP made no mention of space complexity, or indeed constraints on the performance of the algorithm. –  TheJackal 6 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.