39

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

"Hello       World"

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

Phil Hunt
  • 8,404
  • 1
  • 30
  • 25
wiki
  • 2,543
  • 4
  • 19
  • 11

7 Answers7

66
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

Community
  • 1
  • 1
Brosto
  • 4,445
  • 2
  • 34
  • 51
17
var text = "Hello      World";
Console.WriteLine(String.Join(" ", text.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)));
BFree
  • 102,548
  • 21
  • 159
  • 201
11

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));
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
1
var text = "Hello      World";
Regex rex = new Regex(@" {2,}");

rex.Replace(text, " ");
tanathos
  • 5,566
  • 4
  • 34
  • 46
1
    string str = "Hello       World";

    Regex exper=new Regex(@"\s+");
    Console.WriteLine(exper.Replace(str, @" "));
wizzardz
  • 5,664
  • 5
  • 44
  • 66
0

CLEAR EXTRA SPACES BETWEEN A STRING IN ASP. NET C#

SUPPOSE: A NAME IS JITENDRA KUMAR AND I HAVE CLEAR SPACES BETWEEN NAME AND CONVERT THE STRING IN : JITENDRA KUMAR; THEN FOLLOW THIS CODE:

 string PageName= "JITENDRA    KUMAR";
 PageName = txtEmpName.Value.Trim().ToUpper();
 PageName = Regex.Replace(PageName, @"\s+", " ");

 Output string Will be : JITENDRA KUMAR
Code
  • 679
  • 5
  • 9
-2

try this:

string helloWorldString = "Hello    world";

while(helloWorldString.Contains("  "))
 helloWorldString = helloWorldString.Replace("  "," "); 
  • 5
    `Replace` returns the new string, it doesn't mutate the current string. What you have is an infinite loop when `helloWorldString` has a double space. – unholysampler Dec 09 '10 at 16:33