Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove whitespace within string

Tags:

string

c#

.net

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?

like image 536
Rob Avatar asked Apr 19 '11 06:04

Rob


2 Answers

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

Regex.Replace(s, @"\s+", " "); // "This is a string with multiple white space"
like image 107
James Kyburz Avatar answered Sep 28 '22 20:09

James Kyburz


Regex r = new Regex(@"\s+");
string stripped = r.Replace("Too  many    spaces", " ");
like image 36
Jakob Möllås Avatar answered Sep 28 '22 21:09

Jakob Möllås