C# 删除字符串中的空白

C# 删除字符串中的空白,c#,.net,string,C#,.net,String,我有这样的字符串: "This______is_a____string." (“u”表示空格。) 我想把所有的多个空格变成一个。C#中是否有任何函数可以做到这一点?本页上的正则表达式示例可能很好,但这里有一个没有正则表达式的解决方案: var s = "This is a string with multiple white space"; Regex.Replace(s, @"\s+", " "); // "This is a stri

我有这样的字符串:

"This______is_a____string."
(“u”表示空格。)


我想把所有的多个空格变成一个。C#中是否有任何函数可以做到这一点?

本页上的正则表达式示例可能很好,但这里有一个没有正则表达式的解决方案:

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

Regex.Replace(s, @"\s+", " "); // "This is a string with multiple white space"
string myString = "This   is a  string.";
string myNewString = "";
char previousChar = ' ';
foreach(char c in myString)
{
  if (!(previousChar == ' ' && c == ' '))
    myNewString += c;
  previousChar = c;
}

这是一个没有正则表达式的好方法。和林克

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

输出
“这是一个包含多达多个空格的字符串”

@David Agree,需要进行优化,但使用
StringBuilder
或类似工具会使我的示例更难理解。给
myNewString
previousChar
一个初始值也没有得到优化,但我只是想就如何在没有正则表达式的情况下处理这个问题提出一个建议。您也可以使用astring.Split()调用上的StringSplitOptions.RemoveEmptyEntries来删除Where筛选器。
var astring = "This           is      a       string  with     to     many   spaces.";
astring = string.Join(" ", astring.Split(' ').Where(m => m != string.Empty));