如何用c#中的一个空格替换字符串中的多个空格?
例子:
1 2 3 4 5
是:
1 2 3 4 5
如何用c#中的一个空格替换字符串中的多个空格?
例子:
1 2 3 4 5
是:
1 2 3 4 5
当前回答
根据Joel的说法,巩固其他答案,并希望随着我的前进略有改善:
你可以用Regex.Replace()来实现:
string s = Regex.Replace (
" 1 2 4 5",
@"[ ]{2,}",
" "
);
或者使用String.Split():
static class StringExtensions
{
public static string Join(this IList<string> value, string separator)
{
return string.Join(separator, value.ToArray());
}
}
//...
string s = " 1 2 4 5".Split (
" ".ToCharArray(),
StringSplitOptions.RemoveEmptyEntries
).Join (" ");
其他回答
string sentence = "This is a sentence with multiple spaces";
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);
sentence = regex.Replace(sentence, " ");
myString = Regex.Replace(myString, " {2,}", " ");
我知道这很老了,但在尝试完成几乎相同的事情时偶然发现了它。在RegEx Buddy中找到了这个解决方案。该模式将用单个空格替换所有的双空格,并修剪开头和结尾空格。
pattern: (?m:^ +| +$|( ){2,})
replacement: $1
因为我们处理的是空格,所以读起来有点困难,所以这里还是用“_”代替了“空格”。
pattern: (?m:^_+|_+$|(_){2,}) <-- don't use this, just for illustration.
“(?M:" construct启用“多行”选项。我通常喜欢在模式本身中包含任何我可以包含的选项,这样它就更独立了。
string xyz = "1 2 3 4 5";
xyz = string.Join( " ", xyz.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries ));
根据Joel的说法,巩固其他答案,并希望随着我的前进略有改善:
你可以用Regex.Replace()来实现:
string s = Regex.Replace (
" 1 2 4 5",
@"[ ]{2,}",
" "
);
或者使用String.Split():
static class StringExtensions
{
public static string Join(this IList<string> value, string separator)
{
return string.Join(separator, value.ToArray());
}
}
//...
string s = " 1 2 4 5".Split (
" ".ToCharArray(),
StringSplitOptions.RemoveEmptyEntries
).Join (" ");