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

例子:

1 2 3  4    5

是:

1 2 3 4 5

当前回答

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

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

其他回答

我可以用这个删除空格

while word.contains("  ")  //double space
   word = word.Replace("  "," "); //replace double space by single space.
word = word.trim(); //to remove single whitespces from start & end.
// Mysample string
string str ="hi you           are          a demo";

//Split the words based on white sapce
var demo= str .Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));
        
//Join the values back and add a single space in between
str = string.Join(" ", demo);
// output: string str ="hi you are a demo";

我喜欢用:

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

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

使用正则表达式模式

    [ ]+    #only space

   var text = Regex.Replace(inputString, @"[ ]+", " ");

试试这个方法

private string removeNestedWhitespaces(char[] st)
{
    StringBuilder sb = new StringBuilder();
    int indx = 0, length = st.Length;
    while (indx < length)
    {
        sb.Append(st[indx]);
        indx++;
        while (indx < length && st[indx] == ' ')
            indx++;
        if(sb.Length > 1  && sb[0] != ' ')
            sb.Append(' ');
    }
    return sb.ToString();
}

像这样使用它:

string test = removeNestedWhitespaces("1 2 3  4    5".toCharArray());