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

例子:

1 2 3  4    5

是:

1 2 3 4 5

当前回答

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

其他回答

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

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

我喜欢用:

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

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

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

另一种使用LINQ的方法:

 var list = str.Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));
 str = string.Join(" ", list);

许多答案都提供了正确的输出,但对于那些寻找最佳性能的人来说,我确实将Nolanar的答案(性能的最佳答案)提高了大约10%。

public static string MergeSpaces(this string str)
{

    if (str == null)
    {
        return null;
    }
    else
    {
        StringBuilder stringBuilder = new StringBuilder(str.Length);

        int i = 0;
        foreach (char c in str)
        {
            if (c != ' ' || i == 0 || str[i - 1] != ' ')
                stringBuilder.Append(c);
            i++;
        }
        return stringBuilder.ToString();
    }

}