Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace multiple spaces with a single space in C#?

Tags:

string

c#

regex

How can I replace multiple spaces in a string with only one space in C#?

Example:

1 2 3  4    5 

would be:

1 2 3 4 5 
like image 820
Pokus Avatar asked Oct 15 '08 22:10

Pokus


People also ask

How do I replace multiple spaces in single space?

The metacharacter “\s” matches spaces and + indicates the occurrence of the spaces one or more times, therefore, the regular expression \S+ matches all the space characters (single or multiple). Therefore, to replace multiple spaces with a single space.

How do you type spaces in C?

For just a space, use ' ' .


2 Answers

I like to use:

myString = Regex.Replace(myString, @"\s+", " "); 

Since it will catch runs of any kind of whitespace (e.g. tabs, newlines, etc.) and replace them with a single space.

like image 61
Matt Avatar answered Sep 28 '22 08:09

Matt


string sentence = "This is a sentence with multiple    spaces"; RegexOptions options = RegexOptions.None; Regex regex = new Regex("[ ]{2,}", options);      sentence = regex.Replace(sentence, " "); 
like image 41
Patrick Desjardins Avatar answered Sep 28 '22 08:09

Patrick Desjardins