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

例子:

1 2 3  4    5

是:

1 2 3 4 5

当前回答

Regex即使执行简单的任务也会相当慢。这将创建一个可用于任何字符串的扩展方法。

    public static class StringExtension
    {
        public static String ReduceWhitespace(this String value)
        {
            var newString = new StringBuilder();
            bool previousIsWhitespace = false;
            for (int i = 0; i < value.Length; i++)
            {
                if (Char.IsWhiteSpace(value[i]))
                {
                    if (previousIsWhitespace)
                    {
                        continue;
                    }

                    previousIsWhitespace = true;
                }
                else
                {
                    previousIsWhitespace = false;
                }

                newString.Append(value[i]);
            }

            return newString.ToString();
        }
    }

它将被这样使用:

string testValue = "This contains     too          much  whitespace."
testValue = testValue.ReduceWhitespace();
// testValue = "This contains too much whitespace."

其他回答

您可以使用RemoveDoubleSpaces()这样的方法创建StringsExtensions文件。

StringsExtensions.cs

public static string RemoveDoubleSpaces(this string value)  
{
  Regex regex = new Regex("[ ]{2,}", RegexOptions.None);
  value = regex.Replace(value, " ");

  // this removes space at the end of the value (like "demo ")
  // and space at the start of the value (like " hi")
  value = value.Trim(' ');

  return value;
}

然后你可以这样使用它:

string stringInput =" hi here     is  a demo ";

string stringCleaned = stringInput.RemoveDoubleSpaces();

对于那些不喜欢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相比,这应该更快。

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

以下是对Nolonar原始答案的轻微修改。

检查字符是否只是一个空格,而是任何空白,使用这个:

它将用一个空格替换任何多个空白字符。

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

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

根据Joel的说法,巩固其他答案,并希望随着我的前进略有改善:

你可以用Regex.Replace()来实现:

string s = Regex.Replace (
    "   1  2    4 5", 
    @"[ ]{2,}", 
    " "
    );

或者使用String.Split():

static class StringExtensions
{
    public static string Join(this IList<string> value, string separator)
    {
        return string.Join(separator, value.ToArray());
    }
}

//...

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

其实比这简单得多:

while(str.Contains("  ")) str = str.Replace("  ", " ");