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

例子:

1 2 3  4    5

是:

1 2 3 4 5

当前回答

我喜欢用:

myString = Regex.Replace(myString, @"\s+", " ");

因为它将捕获任何类型的空白(例如制表符,换行符等)的运行,并将它们替换为单个空格。

其他回答

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

其实比这简单得多:

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

老派:

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 " ) );

不使用正则表达式:

while (myString.IndexOf("  ", StringComparison.CurrentCulture) != -1)
{
    myString = myString.Replace("  ", " ");
}

可以在短弦上使用,但在有很多空格的长弦上表现不佳。

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."