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

例子:

1 2 3  4    5

是:

1 2 3 4 5

当前回答

我可以用这个删除空格

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

其他回答

我刚刚写了一个我喜欢的新Join,所以我想我应该重新回答,用它:

public static string Join<T>(this IEnumerable<T> source, string separator)
{
    return string.Join(separator, source.Select(e => e.ToString()).ToArray());
}

关于它的一个很酷的事情是,它通过在元素上调用ToString()来处理不是字符串的集合。用法还是一样的:

//...

string s = "     1  2    4 5".Split (
    " ".ToCharArray(), 
    StringSplitOptions.RemoveEmptyEntries
    ).Join (" ");

试试这个方法

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

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

正则表达式。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)

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

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

其实比这简单得多:

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

Regex即使执行简单的任务也会相当慢。这将创建一个可用于任何字符串的扩展方法。

    public static class StringExtension
    {
        public static String ReduceWhitespace(this String value)
        {
            var newString = new StringBuilder();
            bool previousIsWhitespace = false;
            for (int i = 0; i < value.Length; i++)
            {
                if (Char.IsWhiteSpace(value[i]))
                {
                    if (previousIsWhitespace)
                    {
                        continue;
                    }

                    previousIsWhitespace = true;
                }
                else
                {
                    previousIsWhitespace = false;
                }

                newString.Append(value[i]);
            }

            return newString.ToString();
        }
    }

它将被这样使用:

string testValue = "This contains     too          much  whitespace."
testValue = testValue.ReduceWhitespace();
// testValue = "This contains too much whitespace."