11

可能重复:
如何在 C# 中用单个空格替换多个空格?

如何修剪字符串中的空白最优雅的方法是" a<many spaces>b c "into "a b c". 因此,重复的空格被缩小为一个空格。

4

9 回答 9

14

一个没有正则表达式的解决方案,只是为了把它放在桌子上:

char[] delimiters = new char[] { ' '};   // or null for 'all whitespace'
string[] parts = txt.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
string result = String.Join(" ", parts);
于 2012-04-09T08:06:58.570 回答
13

你可以用Regex这个:

Regex.Replace(my_string, @"\s+", " ").Trim();
于 2012-04-09T08:07:23.487 回答
8
Regex.Replace(my_string, @"^\s+|\s+$|(\s)\s+", "$1");
于 2012-04-09T08:11:00.217 回答
4

使用该Trim方法从字符串的开头和结尾删除空格,并使用正则表达式来减少多个空格:

s = Regex.Replace(s.Trim(), @"\s{2,}", " ");
于 2012-04-09T08:17:13.193 回答
2

你可以做一个

Regex.Replace(str, "\\s+", " ").Trim()

http://msdn.microsoft.com/en-us/library/e7f5w83z.aspx

于 2012-04-09T08:09:14.197 回答
0
        Regex rgx = new Regex("\\s+");
        string str;
        str=Console.ReadLine();
        str=rgx.Replace(str," ");
        str = str.Trim();
        Console.WriteLine(str);
于 2012-04-09T09:06:56.903 回答
0
Regex.Replace(str, "[\s]+"," ")

然后调用 Trim 删除前导和尾随空格。

于 2012-04-09T08:09:06.493 回答
0

使用正则表达式

String test = " a    b c ";
test = Regex.Replace(test,@"\s{2,}"," ");
test = test.Trim();

此代码用一个空格替换任何 2 个或多个空格,Regex然后在开头和结尾删除。

于 2012-04-09T08:13:20.253 回答
0

使用正则表达式:

"( ){2,}" //Matches any sequence of spaces, with at least 2 of them

并用它来用“”替换所有匹配项。

我还没有在 C# 中完成它,我需要更多时间来弄清楚文档所说的内容,所以你必须自己找到它......对不起。

于 2012-04-09T08:18:47.237 回答