开发者

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?


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

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


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


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"


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜