如何用c#中的一个空格替换字符串中的多个空格?

例子:

1 2 3  4    5

是:

1 2 3 4 5

当前回答

您可以简单地在一行解决方案中做到这一点!

string s = "welcome to  london";
s.Replace(" ", "()").Replace(")(", "").Replace("()", " ");

如果喜欢,可以选择其他括号(甚至其他字符)。

其他回答

使用正则表达式模式

    [ ]+    #only space

   var text = Regex.Replace(inputString, @"[ ]+", " ");

我知道这很老了,但在尝试完成几乎相同的事情时偶然发现了它。在RegEx Buddy中找到了这个解决方案。该模式将用单个空格替换所有的双空格,并修剪开头和结尾空格。

pattern: (?m:^ +| +$|( ){2,})
replacement: $1

因为我们处理的是空格,所以读起来有点困难,所以这里还是用“_”代替了“空格”。

pattern: (?m:^_+|_+$|(_){2,})  <-- don't use this, just for illustration.

“(?M:" construct启用“多行”选项。我通常喜欢在模式本身中包含任何我可以包含的选项,这样它就更独立了。

老派:

string oldText = "   1 2  3   4    5     ";
string newText = oldText
                    .Replace("  ", " " + (char)22 )
                    .Replace( (char)22 + " ", "" )
                    .Replace( (char)22 + "", "" );

Assert.That( newText, Is.EqualTo( " 1 2 3 4 5 " ) );

我认为Matt的答案是最好的,但我不认为它是完全正确的。如果你想替换换行符,你必须使用:

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

另一种使用LINQ的方法:

 var list = str.Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));
 str = string.Join(" ", list);