如何在 C# 中用单个空格替换多个空格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/206717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 18:01:36  来源:igfitidea点击:

How do I replace multiple spaces with a single space in C#?

c#regexstring

提问by Pokus

How can I replace multiple spaces in a string with only one space in C#?

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

Example:

例子:

1 2 3  4    5

would be:

将是:

1 2 3 4 5

采纳答案by Patrick Desjardins

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

回答by tvanfosson

string xyz = "1   2   3   4   5";
xyz = string.Join( " ", xyz.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries ));

回答by Jay Bazuzi

Consolodating other answers, per Joel, and hopefully improving slightly as I go:

根据乔尔的说法,合并其他答案,并希望随着我的进步而略有改善:

You can do this with Regex.Replace():

你可以这样做Regex.Replace()

string s = Regex.Replace (
    "   1  2    4 5", 
    @"[ ]{2,}", 
    " "
    );

Or with String.Split():

或与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 (" ");

回答by Joel Coehoorn

It's much simpler than all that:

它比所有这些都简单得多:

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

回答by Matt

I like to use:

我喜欢使用:

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

Since it will catch runs of any kind of whitespace (e.g. tabs, newlines, etc.) and replace them with a single space.

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

回答by Jay Bazuzi

I just wrote a new Jointhat I like, so I thought I'd re-answer, with it:

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

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

One of the cool things about this is that it work with collections that aren't strings, by calling ToString() on the elements. Usage is still the same:

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

//...

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

回答by Jan Goyvaerts

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

回答by Brenda Bell

I think Matt's answer is the best, but I don't believe it's quite right. If you want to replace newlines, you must use:

我认为马特的答案是最好的,但我认为这不太正确。如果要替换换行符,必须使用:

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

回答by cuongle

Another approach which uses LINQ:

另一种使用 LINQ 的方法:

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

回答by onedaywhen

Old skool:

老学校:

string oldText = "   1 2  3   4    5     ";
string newText = oldText
                    .Replace("  ", " " + (char)22 )
                    .Replace( (char)22 + " ", "" )
                    .Replace( (char)22 + "", "" );

Assert.That( newText, Is.EqualTo( " 1 2 3 4 5 " ) );