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

例子:

1 2 3  4    5

是:

1 2 3 4 5

当前回答

我仔细查看了建议的解决方案,但没有找到一个可以处理我的情况下可接受的空白字符的混合,例如:

正则表达式。Replace(input, @"\s+", " " ") -它将吃掉你的换行符,如果它们与空格混合,例如\n \n序列将被替换为 正则表达式。Replace(source, @"(\s)\s+", "$1") -它将依赖于空格的第一个字符,这意味着它可能再次吃掉你的换行符 正则表达式。Replace(source, @"[]{2,}", " ") -当有混合空白字符时,它将无法正常工作-例如"\t \t "

可能并不完美,但对我来说快速的解决方法是:

Regex.Replace(input, @"\s+", 
(match) => match.Value.IndexOf('\n') > -1 ? "\n" : " ", RegexOptions.Multiline)

思想是换行胜过空格和制表符。

这不会正确地处理窗口换行,但它也很容易调整工作,不知道正则表达式那么好-可能是有可能适合单一模式。

其他回答

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

您可以简单地在一行解决方案中做到这一点!

string s = "welcome to  london";
s.Replace(" ", "()").Replace(")(", "").Replace("()", " ");

如果喜欢,可以选择其他括号(甚至其他字符)。

试试这个方法

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

这是一个更短的版本,只有在只执行一次时才应该使用,因为每次调用Regex类时都会创建一个新的实例。

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

如果你不太熟悉正则表达式,这里有一个简短的解释:

{2,}使正则表达式搜索它前面的字符,并在2到无限次之间查找子字符串。 . replace (temp, " ")将字符串temp中的所有匹配项替换为空格。

如果你想多次使用这个,这里有一个更好的选择,因为它在编译时创建正则表达式IL:

Regex singleSpacify = new Regex(" {2,}", RegexOptions.Compiled);
temp = singleSpacify.Replace(temp, " ");
string sentence = "This is a sentence with multiple    spaces";
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);     
sentence = regex.Replace(sentence, " ");