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

例子:

1 2 3  4    5

是:

1 2 3 4 5

当前回答

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

其他回答

我可以用这个删除空格

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

没有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”

根据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 (" ");

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

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

要不耍流氓?

public static string MinimizeWhiteSpace(
    this string _this)
    {
        if (_this != null)
        {
            var returned = new StringBuilder();
            var inWhiteSpace = false;
            var length = _this.Length;
            for (int i = 0; i < length; i++)
            {
                var character = _this[i];
                if (char.IsWhiteSpace(character))
                {
                    if (!inWhiteSpace)
                    {
                        inWhiteSpace = true;
                        returned.Append(' ');
                    }
                }
                else
                {
                    inWhiteSpace = false;
                    returned.Append(character);
                }
            }
            return returned.ToString();
        }
        else
        {
            return null;
        }
    }