Siddharth Rajput
Siddharth Rajput

Reputation: 83

How to remove extra spaces between two words in a string?

ViewBag.Title = "Hello (123) world"

what I want is:

"Hello 123 world"

Here is my code:

string input = ViewBag.Title;
System.Text.RegularExpressions.Regex re = new 
System.Text.RegularExpressions.Regex("[;\\\\/:*?\"<>|&'()-]");
ViewBag.MetaTitle = re.Replace(input, " "); //" " only one space here

Using this, I am getting:

Hello  123  world

There is extra one space between "hello" and "123" and "world" due to brackets. How can I remove those extra spaces?

Upvotes: 2

Views: 256

Answers (3)

user1859022
user1859022

Reputation: 2685

from the comments in @SCoutos answer the OP wants replace certain chars with spaces but only if the there is no spacing around the char

modify the regex to:

"\\s?[;\\\\/:*?\"<>|&'()-]+\\s?"

so for Hello World (707(y)(9) you get

Hello World 707 y 9

Example code:

const string TARGET_STRING = "Hello World (707(y)(9)";
var regEx = new Regex("\\s?[;\\\\/:*?\"<>|&'()-]+\\s?");
string result = regEx.Replace(TARGET_STRING, " ");

see: https://dotnetfiddle.net/KpFY6X

Upvotes: 2

Stefan
Stefan

Reputation: 17658

As an alternative, split and rebuilt your string:

string input = "Hello world (707)(y)(9) ";
System.Text.RegularExpressions.Regex re = new
System.Text.RegularExpressions.Regex("[;\\\\/:*?\"<>|&'()-]");
//split
var x = re.Split(input);
//rebuild
var newString = string.Join(" ", x.Where(c => !string.IsNullOrWhiteSpace(c))
                                  .Select(c => c.Trim()));

newString equals:

Hello world 707 y 9

Upvotes: 4

SCouto
SCouto

Reputation: 7928

Replacing the unwanted characters by a blank string will do the trick:

ViewBag.MetaTitle = re.Replace(input, "");

Upvotes: 1

Related Questions