Reputation: 2553
How to remove extra space between two words using C#? Consider:
"Hello World"
I want this to be manipulated as "Hello World"
.
Upvotes: 39
Views: 48742
Reputation: 739
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
Upvotes: 0
Reputation: 262989
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));
Upvotes: 11
Reputation: 5874
string str = "Hello World";
Regex exper=new Regex(@"\s+");
Console.WriteLine(exper.Replace(str, @" "));
Upvotes: 1
Reputation: 5606
var text = "Hello World";
Regex rex = new Regex(@" {2,}");
rex.Replace(text, " ");
Upvotes: 1
Reputation: 63
try this:
string helloWorldString = "Hello world";
while(helloWorldString.Contains(" "))
helloWorldString = helloWorldString.Replace(" "," ");
Upvotes: -2
Reputation: 4565
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
Upvotes: 68
Reputation: 103740
var text = "Hello World";
Console.WriteLine(String.Join(" ", text.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)));
Upvotes: 17