How do I replace multiple spaces with a single spa

2018-12-31 10:49发布

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

Example:

1 2 3  4    5

would be:

1 2 3 4 5

标签: c# regex string
22条回答
闭嘴吧你
2楼-- · 2018-12-31 11:00

Use the regex pattern

    [ ]+    #only space

   var text = Regex.Replace(inputString, @"[ ]+", " ");
查看更多
永恒的永恒
3楼-- · 2018-12-31 11:04

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

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:

//...

string s = "     1  2    4 5".Split (
    " ".ToCharArray(), 
    StringSplitOptions.RemoveEmptyEntries
    ).Join (" ");
查看更多
不再属于我。
4楼-- · 2018-12-31 11:05

You can simply do this in one line solution!

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

You can choose other brackets (or even other characters) if you like.

查看更多
几人难应
5楼-- · 2018-12-31 11:07

Without using regular expressions:

while (myString.IndexOf("  ", StringComparison.CurrentCulture) != -1)
{
    myString = myString.Replace("  ", " ");
}

OK to use on short strings, but will perform badly on long strings with lots of spaces.

查看更多
残风、尘缘若梦
6楼-- · 2018-12-31 11:08

I can remove whitespaces with this

while word.contains("  ")  //double space
   word = word.Replace("  "," "); //replace double space by single space.
word = word.trim(); //to remove single whitespces from start & end.
查看更多
只若初见
7楼-- · 2018-12-31 11:09
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);     
tempo = regex.Replace(tempo, " ");
查看更多
登录 后发表回答