如何用c#中的一个空格替换字符串中的多个空格?
例子:
1 2 3 4 5
是:
1 2 3 4 5
如何用c#中的一个空格替换字符串中的多个空格?
例子:
1 2 3 4 5
是:
1 2 3 4 5
当前回答
下面的代码将所有多个空格删除为一个空格
public string RemoveMultipleSpacesToSingle(string str)
{
string text = str;
do
{
//text = text.Replace(" ", " ");
text = Regex.Replace(text, @"\s+", " ");
} while (text.Contains(" "));
return text;
}
其他回答
这是一个更短的版本,只有在只执行一次时才应该使用,因为每次调用Regex类时都会创建一个新的实例。
temp = new Regex(" {2,}").Replace(temp, " ");
如果你不太熟悉正则表达式,这里有一个简短的解释:
{2,}使正则表达式搜索它前面的字符,并在2到无限次之间查找子字符串。 . replace (temp, " ")将字符串temp中的所有匹配项替换为空格。
如果你想多次使用这个,这里有一个更好的选择,因为它在编译时创建正则表达式IL:
Regex singleSpacify = new Regex(" {2,}", RegexOptions.Compiled);
temp = singleSpacify.Replace(temp, " ");
对于那些不喜欢Regex的人,这里有一个使用StringBuilder的方法:
public static string FilterWhiteSpaces(string input)
{
if (input == null)
return string.Empty;
StringBuilder stringBuilder = new StringBuilder(input.Length);
for (int i = 0; i < input.Length; i++)
{
char c = input[i];
if (i == 0 || c != ' ' || (c == ' ' && input[i - 1] != ' '))
stringBuilder.Append(c);
}
return stringBuilder.ToString();
}
在我的测试中,与静态编译的Regex相比,这种方法在非常大的中小型字符串集上平均快16倍。与非编译或非静态Regex相比,这应该更快。
请记住,它不会删除前导空格或尾随空格,只会多次删除此类空格。
您可以简单地在一行解决方案中做到这一点!
string s = "welcome to london";
s.Replace(" ", "()").Replace(")(", "").Replace("()", " ");
如果喜欢,可以选择其他括号(甚至其他字符)。
Regex即使执行简单的任务也会相当慢。这将创建一个可用于任何字符串的扩展方法。
public static class StringExtension
{
public static String ReduceWhitespace(this String value)
{
var newString = new StringBuilder();
bool previousIsWhitespace = false;
for (int i = 0; i < value.Length; i++)
{
if (Char.IsWhiteSpace(value[i]))
{
if (previousIsWhitespace)
{
continue;
}
previousIsWhitespace = true;
}
else
{
previousIsWhitespace = false;
}
newString.Append(value[i]);
}
return newString.ToString();
}
}
它将被这样使用:
string testValue = "This contains too much whitespace."
testValue = testValue.ReduceWhitespace();
// testValue = "This contains too much whitespace."
我知道这很老了,但在尝试完成几乎相同的事情时偶然发现了它。在RegEx Buddy中找到了这个解决方案。该模式将用单个空格替换所有的双空格,并修剪开头和结尾空格。
pattern: (?m:^ +| +$|( ){2,})
replacement: $1
因为我们处理的是空格,所以读起来有点困难,所以这里还是用“_”代替了“空格”。
pattern: (?m:^_+|_+$|(_){2,}) <-- don't use this, just for illustration.
“(?M:" construct启用“多行”选项。我通常喜欢在模式本身中包含任何我可以包含的选项,这样它就更独立了。