5

what is the efficient mechanism to remove 2 or more white spaces from a string leaving single white space.

I mean if string is "a____b" the output must be "a_b".

1
  • Are you asking, if someone accidentally double spaces how can you correct all instances of that? Jun 8, 2011 at 6:00

4 Answers 4

8

You can use a regular expression to replace multiple spaces:

s = Regex.Replace(s, " {2,}", " ");
3
  • 1
    @Nick: Yes. The quantifier {2,} makes the expression match two or more spaces.
    – Guffa
    Jun 8, 2011 at 6:04
  • what do the literals actually imply, I mean in {2,} what does the 2 represent and why there is nothing after the comma. Just getting a complete view on solution. Jun 8, 2011 at 6:27
  • 1
    @Gunner = {2,} means two or more. Leaving out the upper limit, it can be any number. {2,5} would have meant between 2 and 5 inclusive.
    – manojlds
    Jun 8, 2011 at 6:37
3

Something like below maybe:

var b=a.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
var noMultipleSpaces = string.Join(" ",b);
0
1
string tempo = "this    is    a     string    with    spaces";
RegexOptions options = RegexOptions.None;
Regex regex = new Regex(@"[ ]{2,}", options);     
tempo = regex.Replace(tempo, @" ");
0

You Can user this method n pass your string value as argument you have to add one namespace also using System.Text.RegularExpressions;

public static string RemoveMultipleWhiteSpace(string str)

{



    // A.
    // Create the Regex.
    Regex r = new Regex(@"\s+");

    // B.
    // Remove multiple spaces.
    string s3 = r.Replace(str, @" ");
    return s3;

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.