patterncsharpMajor
Replace each whitespace in a string with "%20"
Viewed 0 times
eachwhitespacewithreplacestring
Problem
My implementation:
Input:
Output:
How could this be improved? Only ASCII characters are permitted.
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.
Solution
This one really fits well for a regular expression:
The expression
The pattern matches "one or more whitespace characters", so it will match each group of whitespace characters (for example the six spaces between
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.Code Snippets
public static string ReplaceAllSpaces(string str) {
return Regex.Replace(str, @"\s+","%20");
}Context
StackExchange Code Review Q#64935, answer score: 40
Revisions (0)
No revisions yet.