假设我有一个字符串,比如:
"Hello how are you doing?"
我想要一个能把多个空格变成一个空格的函数。
所以我会得到:
"Hello how are you doing?"
我知道我可以使用regex或call
string s = "Hello how are you doing?".replace(" "," ");
但我必须多次调用它,以确保所有连续的空格都被替换为一个空格。
有没有内置的方法来解决这个问题呢?
发布于 2009-08-14 19:57:50
string cleanedString = System.Text.RegularExpressions.Regex.Replace(dirtyString,@"\s+"," ");
发布于 2009-08-14 19:58:38
一个常规的表达式将是最简单的方法。如果您以正确的方式编写正则表达式,则不需要多次调用。
将其更改为:
string s = System.Text.RegularExpressions.Regex.Replace(s, @"\s{2,}", " ");
发布于 2014-12-16 18:23:54
这是我使用的解决方案。没有RegEx和String.Split。
public static string TrimWhiteSpace(this string Value)
{
StringBuilder sbOut = new StringBuilder();
if (!string.IsNullOrEmpty(Value))
{
bool IsWhiteSpace = false;
for (int i = 0; i < Value.Length; i++)
{
if (char.IsWhiteSpace(Value[i])) //Comparion with WhiteSpace
{
if (!IsWhiteSpace) //Comparison with previous Char
{
sbOut.Append(Value[i]);
IsWhiteSpace = true;
}
}
else
{
IsWhiteSpace = false;
sbOut.Append(Value[i]);
}
}
}
return sbOut.ToString();
}
因此,您可以:
string cleanedString = dirtyString.TrimWhiteSpace();
https://stackoverflow.com/questions/1279859
复制相似问题