Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove extra space between two words using C#?

Tags:

string

c#

How to remove extra space between two words using C#? Consider:

"Hello       World" 

I want this to be manipulated as "Hello World".

like image 217
wiki Avatar asked Dec 09 '10 16:12

wiki


People also ask

How do I remove spaces between words in a string?

In Java, we can use regex \\s+ to match whitespace characters, and replaceAll("\\s+", " ") to replace them with a single space.

How do I remove double spacing from a string?

Using regexes with "\s" and doing simple string. split()'s will also remove other whitespace - like newlines, carriage returns, tabs.


2 Answers

RegexOptions options = RegexOptions.None; Regex regex = new Regex(@"[ ]{2,}", options);      tempo = regex.Replace(tempo, @" "); 

or even:

myString = Regex.Replace(myString, @"\s+", " "); 

both pulled from here

like image 149
Brosto Avatar answered Sep 16 '22 23:09

Brosto


var text = "Hello      World"; Console.WriteLine(String.Join(" ", text.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries))); 
like image 31
BFree Avatar answered Sep 19 '22 23:09

BFree