如何用c#中的一个空格替换字符串中的多个空格?
例子:
1 2 3 4 5
是:
1 2 3 4 5
如何用c#中的一个空格替换字符串中的多个空格?
例子:
1 2 3 4 5
是:
1 2 3 4 5
当前回答
string xyz = "1 2 3 4 5";
xyz = string.Join( " ", xyz.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries ));
其他回答
使用正则表达式模式
[ ]+ #only space
var text = Regex.Replace(inputString, @"[ ]+", " ");
您可以使用RemoveDoubleSpaces()这样的方法创建StringsExtensions文件。
StringsExtensions.cs
public static string RemoveDoubleSpaces(this string value)
{
Regex regex = new Regex("[ ]{2,}", RegexOptions.None);
value = regex.Replace(value, " ");
// this removes space at the end of the value (like "demo ")
// and space at the start of the value (like " hi")
value = value.Trim(' ');
return value;
}
然后你可以这样使用它:
string stringInput =" hi here is a demo ";
string stringCleaned = stringInput.RemoveDoubleSpaces();
不使用正则表达式:
while (myString.IndexOf(" ", StringComparison.CurrentCulture) != -1)
{
myString = myString.Replace(" ", " ");
}
可以在短弦上使用,但在有很多空格的长弦上表现不佳。
下面的代码将所有多个空格删除为一个空格
public string RemoveMultipleSpacesToSingle(string str)
{
string text = str;
do
{
//text = text.Replace(" ", " ");
text = Regex.Replace(text, @"\s+", " ");
} while (text.Contains(" "));
return text;
}
我知道这很老了,但在尝试完成几乎相同的事情时偶然发现了它。在RegEx Buddy中找到了这个解决方案。该模式将用单个空格替换所有的双空格,并修剪开头和结尾空格。
pattern: (?m:^ +| +$|( ){2,})
replacement: $1
因为我们处理的是空格,所以读起来有点困难,所以这里还是用“_”代替了“空格”。
pattern: (?m:^_+|_+$|(_){2,}) <-- don't use this, just for illustration.
“(?M:" construct启用“多行”选项。我通常喜欢在模式本身中包含任何我可以包含的选项,这样它就更独立了。