35

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,356
  • 1
  • 29
  • 25
wiki
  • 2,443
  • 4
  • 18
  • 11

7 Answers7

60
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,235
  • 2
  • 32
  • 51
15
var text = "Hello      World";
Console.WriteLine(String.Join(" ", text.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)));
BFree
  • 100,265
  • 20
  • 154
  • 199
10

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
  • 249,845
  • 40
  • 466
  • 467
1
var text = "Hello      World";
Regex rex = new Regex(@" {2,}");

rex.Replace(text, " ");
tanathos
  • 5,486
  • 4
  • 32
  • 45
1
    string str = "Hello       World";

    Regex exper=new Regex(@"\s+");
    Console.WriteLine(exper.Replace(str, @" "));
wizzardz
  • 5,306
  • 5
  • 42
  • 65
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
  • 559
  • 4
  • 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