Replace each whitespace in a string with "%20" 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.
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.