Rob
Rob

Reputation: 7216

Remove whitespace within string

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?

Upvotes: 6

Views: 3315

Answers (4)

Jakob Möllås
Jakob Möllås

Reputation: 4369

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

Upvotes: 5

Theun Arbeider
Theun Arbeider

Reputation: 5409

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"

Upvotes: 3

Bazzz
Bazzz

Reputation: 26912

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;
}

Upvotes: 2

James Kyburz
James Kyburz

Reputation: 14453

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

Regex.Replace(s, @"\s+", " "); // "This is a string with multiple white space"

Upvotes: 11

Related Questions