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

var text = "Hello      World";
Regex rex = new Regex(@" {2,}");

rex.Replace(text, " ");

var text = "Hello      World";
Console.WriteLine(String.Join(" ", text.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)));

You can pass options to String.Split() to tell it to collapse consecutive separator characters, so you can write:

string expr = "Hello      World";
expr = String.Join(" ", expr.Split(new char[] { ' ' },
    StringSplitOptions.RemoveEmptyEntries));

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

Tags:

C#

String