如何用c#中的一个空格替换字符串中的多个空格?
例子:
1 2 3 4 5
是:
1 2 3 4 5
如何用c#中的一个空格替换字符串中的多个空格?
例子:
1 2 3 4 5
是:
1 2 3 4 5
当前回答
我知道这很老了,但在尝试完成几乎相同的事情时偶然发现了它。在RegEx Buddy中找到了这个解决方案。该模式将用单个空格替换所有的双空格,并修剪开头和结尾空格。
pattern: (?m:^ +| +$|( ){2,})
replacement: $1
因为我们处理的是空格,所以读起来有点困难,所以这里还是用“_”代替了“空格”。
pattern: (?m:^_+|_+$|(_){2,}) <-- don't use this, just for illustration.
“(?M:" construct启用“多行”选项。我通常喜欢在模式本身中包含任何我可以包含的选项,这样它就更独立了。
其他回答
没有Regex,没有Linq…删除开头和结尾空格,并将任何嵌入的多个空格段减少为一个空格
string myString = " 0 1 2 3 4 5 ";
myString = string.Join(" ", myString.Split(new char[] { ' ' },
StringSplitOptions.RemoveEmptyEntries));
结果:“0 1 2 3 4 5”
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."
我刚刚写了一个我喜欢的新Join,所以我想我应该重新回答,用它:
public static string Join<T>(this IEnumerable<T> source, string separator)
{
return string.Join(separator, source.Select(e => e.ToString()).ToArray());
}
关于它的一个很酷的事情是,它通过在元素上调用ToString()来处理不是字符串的集合。用法还是一样的:
//...
string s = " 1 2 4 5".Split (
" ".ToCharArray(),
StringSplitOptions.RemoveEmptyEntries
).Join (" ");
许多答案都提供了正确的输出,但对于那些寻找最佳性能的人来说,我确实将Nolanar的答案(性能的最佳答案)提高了大约10%。
public static string MergeSpaces(this string str)
{
if (str == null)
{
return null;
}
else
{
StringBuilder stringBuilder = new StringBuilder(str.Length);
int i = 0;
foreach (char c in str)
{
if (c != ' ' || i == 0 || str[i - 1] != ' ')
stringBuilder.Append(c);
i++;
}
return stringBuilder.ToString();
}
}
我喜欢用:
myString = Regex.Replace(myString, @"\s+", " ");
因为它将捕获任何类型的空白(例如制表符,换行符等)的运行,并将它们替换为单个空格。