views:

11376

answers:

11

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"?
+34  A: 
RegexOptions options = RegexOptions.None;
Regex regex = new Regex(@"[ ]{2,}", options);     
tempo = regex.Replace(tempo, @" ");
Daok
I have copy and paste that and it works. I really do not like REgex but this time it saves my life.
Pokus
This is good solution but unless you wrap it in a method most programmers will have no idea what it does.
Craig
@Craig a comment would suffice, IMO. // This block replaces multiple spaces with one... :)
paulwhit
@Pokus, RegEx is a wonderfully powerful tool to learn and use, once you just get past the initial learning curve, you'll wonder how you ever lived without it.
Mark
There's minor bug, should be @" ", not @"".
DK
Really, RegEx is overkill for this.
Joel Coehoorn
You don't need the square brackets in the regex. Just use " {2,}".
Jan Goyvaerts
But now you have 2 problems....
seanb
@Joel: Can't agree. I'm actually sure that this way is more efficient than yours for large enough strings and can be done in one single line. Where's the overkill?
Konrad Rudolph
lacop
The Regex could be compiled since it can be reused in its form.
Andrei Rinea
+5  A: 
string xyz = "1   2   3   4   5";
xyz = string.Join( " ", xyz.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries ));
tvanfosson
Regex works too.
tvanfosson
A: 
while (str.IndexOf("  ") != -1)
  str = str.Replace("  ", " ");

Non regex way.

Craig
<> work in C#, I thought is was !=
Pokus
Replace uses a regex...i think...no big deal though
jjnguy
Your right, != is correct in C#. Too many languages running through my head!
Craig
This method will createas many strings in memory as there are double-space occurrences in the string. Not good.
Robert C. Barth
A: 

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

You can do this with Regex.Replace():

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

Or with 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 (" ");
Jay Bazuzi
+2  A: 

It's much simpler than all that:

while(str.Contains("  ")) str = str.Replace("  ", " ");
Joel Coehoorn
This will be far less efficient than the regex " {2,}" if the string contains sequences of 3 or more spaces.
Jan Goyvaerts
+43  A: 

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.

Matt
fav ............(15 characters)
Xster
A: 

If this is in a lengthy loop with optimization concerns, I would suggest doing a timing comparison of the given solutions with a simple char array copy that skips the extra spaces.

pro3carp3
A: 

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 (" ");
Jay Bazuzi
why create an extension method? why not just use string.Join()?
spoon16
+2  A: 
myString = Regex.Replace(myString, " {2,}", " ");
Jan Goyvaerts
A: 

thanks.. this thread helped me a lot

+1  A: 

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);
Brenda Bell