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

例子:

1 2 3  4    5

是:

1 2 3 4 5

当前回答

没有Regex,没有Linq…删除开头和结尾空格,并将任何嵌入的多个空格段减少为一个空格

string myString = "   0 1 2  3   4               5  ";
myString = string.Join(" ", myString.Split(new char[] { ' ' }, 
StringSplitOptions.RemoveEmptyEntries));

结果:“0 1 2 3 4 5”

其他回答

我刚刚写了一个我喜欢的新Join,所以我想我应该重新回答,用它:

public static string Join<T>(this IEnumerable<T> source, string separator)
{
    return string.Join(separator, source.Select(e => e.ToString()).ToArray());
}

关于它的一个很酷的事情是,它通过在元素上调用ToString()来处理不是字符串的集合。用法还是一样的:

//...

string s = "     1  2    4 5".Split (
    " ".ToCharArray(), 
    StringSplitOptions.RemoveEmptyEntries
    ).Join (" ");

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

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

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

混合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的人,这里有一个使用StringBuilder的方法:

    public static string FilterWhiteSpaces(string input)
    {
        if (input == null)
            return string.Empty;

        StringBuilder stringBuilder = new StringBuilder(input.Length);
        for (int i = 0; i < input.Length; i++)
        {
            char c = input[i];
            if (i == 0 || c != ' ' || (c == ' ' && input[i - 1] != ' '))
                stringBuilder.Append(c);
        }
        return stringBuilder.ToString();
    }

在我的测试中,与静态编译的Regex相比,这种方法在非常大的中小型字符串集上平均快16倍。与非编译或非静态Regex相比,这应该更快。

请记住,它不会删除前导空格或尾随空格,只会多次删除此类空格。

我可以用这个删除空格

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