6

I have strings like this:

"This______is_a____string."

(The "_" symbolizes spaces.)

I want to turn all the multiple spaces into only one. Are there any functions in C# that can do this?

4 Answers 4

11
var s = "This   is    a     string    with multiple    white   space";

Regex.Replace(s, @"\s+", " "); // "This is a string with multiple white space"
Sign up to request clarification or add additional context in comments.

Comments

5
Regex r = new Regex(@"\s+");
string stripped = r.Replace("Too  many    spaces", " ");

Comments

3

Here's a nice way without regex. With Linq.

var astring = "This           is      a       string  with     to     many   spaces.";
astring = string.Join(" ", astring.Split(' ').Where(m => m != string.Empty));

output "This is a string with to many spaces"

1 Comment

You can also use StringSplitOptions.RemoveEmptyEntries on the astring.Split() call to remove your Where filter.
2

The regex examples on this page are probably good but here is a solution without regex:

string myString = "This   is a  string.";
string myNewString = "";
char previousChar = ' ';
foreach(char c in myString)
{
  if (!(previousChar == ' ' && c == ' '))
    myNewString += c;
  previousChar = c;
}

1 Comment

@David Agree, there are optimalisations to make, but using a StringBuilder, or the like, would have made my example more difficult to understand. Giving myNewString and previousChar an initial value is also not optimised, but I'm merely trying to make a suggestion as to how to approach the issue without regex. Feel free to make it "perfect" :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.