去除字符串中的空格

6

我有这样的字符串:

"This______is_a____string."

("_"代表空格)

我想把所有多余的空格变成一个。在C#中有没有可以做到这一点的函数?

4个回答

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

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

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

3
这是一种不需要使用正则表达式的简便方法。可以使用Linq实现。
var astring = "This           is      a       string  with     to     many   spaces.";
astring = string.Join(" ", astring.Split(' ').Where(m => m != string.Empty));

输出 "这是一个带有太多空格的字符串"


2
您还可以在astring.Split()调用上使用StringSplitOptions.RemoveEmptyEntries来删除Where过滤器。 - ahawker

2
这个页面上的正则表达式示例可能很好,但这里有一个不需要使用正则表达式的解决方案:
string myString = "This   is a  string.";
string myNewString = "";
char previousChar = ' ';
foreach(char c in myString)
{
  if (!(previousChar == ' ' && c == ' '))
    myNewString += c;
  previousChar = c;
}

@David 同意,有一些优化可以做,但使用 StringBuilder 或类似的东西会使我的示例更难理解。给 myNewStringpreviousChar 赋一个初始值也不是最优的,但我只是试图提出一些不使用正则表达式的解决问题的建议。请随意将其变得“完美” :) - Bazzz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接