Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 703
Ajit Avatar asked Jun 08 '11 05:06

Ajit


People also ask

What removes extra white spaces before and after the string?

You can call the trim() method on your string to remove whitespace from the beginning and end of it. It returns a new string.

How do you remove all white spaces at the end of the string?

trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.


3 Answers

You can use a regular expression to replace multiple spaces:

s = Regex.Replace(s, " {2,}", " ");
like image 168
Guffa Avatar answered Nov 04 '22 02:11

Guffa


Something like below maybe:

var b=a.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
var noMultipleSpaces = string.Join(" ",b);
like image 26
manojlds Avatar answered Nov 04 '22 00:11

manojlds


string tempo = "this    is    a     string    with    spaces";
RegexOptions options = RegexOptions.None;
Regex regex = new Regex(@"[ ]{2,}", options);     
tempo = regex.Replace(tempo, @" ");
like image 21
RubenHerman Avatar answered Nov 04 '22 02:11

RubenHerman