如何用c#中的一个空格替换字符串中的多个空格?
例子:
1 2 3 4 5
是:
1 2 3 4 5
如何用c#中的一个空格替换字符串中的多个空格?
例子:
1 2 3 4 5
是:
1 2 3 4 5
当前回答
这是一个更短的版本,只有在只执行一次时才应该使用,因为每次调用Regex类时都会创建一个新的实例。
temp = new Regex(" {2,}").Replace(temp, " ");
如果你不太熟悉正则表达式,这里有一个简短的解释:
{2,}使正则表达式搜索它前面的字符,并在2到无限次之间查找子字符串。 . replace (temp, " ")将字符串temp中的所有匹配项替换为空格。
如果你想多次使用这个,这里有一个更好的选择,因为它在编译时创建正则表达式IL:
Regex singleSpacify = new Regex(" {2,}", RegexOptions.Compiled);
temp = singleSpacify.Replace(temp, " ");
其他回答
使用正则表达式模式
[ ]+ #only space
var text = Regex.Replace(inputString, @"[ ]+", " ");
// Mysample string
string str ="hi you are a demo";
//Split the words based on white sapce
var demo= str .Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));
//Join the values back and add a single space in between
str = string.Join(" ", demo);
// output: string str ="hi you are a demo";
这是一个更短的版本,只有在只执行一次时才应该使用,因为每次调用Regex类时都会创建一个新的实例。
temp = new Regex(" {2,}").Replace(temp, " ");
如果你不太熟悉正则表达式,这里有一个简短的解释:
{2,}使正则表达式搜索它前面的字符,并在2到无限次之间查找子字符串。 . replace (temp, " ")将字符串temp中的所有匹配项替换为空格。
如果你想多次使用这个,这里有一个更好的选择,因为它在编译时创建正则表达式IL:
Regex singleSpacify = new Regex(" {2,}", RegexOptions.Compiled);
temp = singleSpacify.Replace(temp, " ");
string sentence = "This is a sentence with multiple spaces";
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);
sentence = regex.Replace(sentence, " ");
我认为Matt的答案是最好的,但我不认为它是完全正确的。如果你想替换换行符,你必须使用:
myString = Regex.Replace(myString, @"\s+", " ", RegexOptions.Multiline);