Ajit
Ajit

Reputation: 319

Remove 2 or more blank spaces from a string in c#..?

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".

Upvotes: 5

Views: 1712

Answers (4)

AB Vyas
AB Vyas

Reputation: 2389

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;

}

Upvotes: 0

RubenHerman
RubenHerman

Reputation: 1854

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

Upvotes: 1

manojlds
manojlds

Reputation: 301527

Something like below maybe:

var b=a.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
var noMultipleSpaces = string.Join(" ",b);

Upvotes: 3

Guffa
Guffa

Reputation: 700800

You can use a regular expression to replace multiple spaces:

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

Upvotes: 8

Related Questions