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

例子:

1 2 3  4    5

是:

1 2 3 4 5

当前回答

其实比这简单得多:

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

其他回答

不使用正则表达式:

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

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

根据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 (" ");
string xyz = "1   2   3   4   5";
xyz = string.Join( " ", xyz.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries ));

您可以使用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();

我认为Matt的答案是最好的,但我不认为它是完全正确的。如果你想替换换行符,你必须使用:

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