简体   繁体   中英

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?

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

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

用空字符串替换不需要的字符就可以了:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM