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

例子:

1 2 3  4    5

是:

1 2 3 4 5

当前回答

下面的代码将所有多个空格删除为一个空格

    public string RemoveMultipleSpacesToSingle(string str)
    {
        string text = str;
        do
        {
            //text = text.Replace("  ", " ");
            text = Regex.Replace(text, @"\s+", " ");
        } while (text.Contains("  "));
        return text;
    }

其他回答

我可以用这个删除空格

while word.contains("  ")  //double space
   word = word.Replace("  "," "); //replace double space by single space.
word = word.trim(); //to remove single whitespces from start & end.

混合StringBuilder和Enumerable.Aggregate()作为字符串的扩展方法:

using System;
using System.Linq;
using System.Text;

public static class StringExtension
{
    public static string CondenseSpaces(this string s)
    {
        return s.Aggregate(new StringBuilder(), (acc, c) =>
        {
            if (c != ' ' || acc.Length == 0 || acc[acc.Length - 1] != ' ')
                acc.Append(c);
            return acc;
        }).ToString();
    }

    public static void Main()
    {
        const string input = "     (five leading spaces)     (five internal spaces)     (five trailing spaces)     ";
        
        Console.WriteLine(" Input: \"{0}\"", input);
        Console.WriteLine("Output: \"{0}\"", StringExtension.CondenseSpaces(input));
    }
}

执行这个程序产生以下输出:

 Input: "     (five leading spaces)     (five internal spaces)     (five trailing spaces)     "
Output: " (five leading spaces) (five internal spaces) (five trailing spaces) "

我知道这很老了,但在尝试完成几乎相同的事情时偶然发现了它。在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 " ) );

这是一个更短的版本,只有在只执行一次时才应该使用,因为每次调用Regex类时都会创建一个新的实例。

temp = new Regex(" {2,}").Replace(temp, " "); 

如果你不太熟悉正则表达式,这里有一个简短的解释:

{2,}使正则表达式搜索它前面的字符,并在2到无限次之间查找子字符串。 . replace (temp, " ")将字符串temp中的所有匹配项替换为空格。

如果你想多次使用这个,这里有一个更好的选择,因为它在编译时创建正则表达式IL:

Regex singleSpacify = new Regex(" {2,}", RegexOptions.Compiled);
temp = singleSpacify.Replace(temp, " ");