我有很多这样的字符串:
current affairs
我希望你能将字符串变为:
current affairs
我尝试使用
Trim()
,但它并不能完成工作。我有很多这样的字符串:
current affairs
我希望你能将字符串变为:
current affairs
Trim()
,但它并不能完成工作。正则表达式可以胜任这个工作
string_text = Regex.Replace(string_text, @"\s+", " ");
Regex.Replace(myString, "\\s{2,}", "")
,这样你就不会把单个空格替换为它们自己。在我的测试中可以提高约30%的效果。 - JoeyRegex.Replace
:var normalizedString = Regex.Replace(myString, " +", " ");
@"\s+"
而不是仅处理空格的"+"
。var normalizedString = Regex.Replace(myString, @"\s+", " ");
yourString= Regex.Replace(yourString, @"\s+", " ");
public string RemoveMultipleSpaces(string s)
{
return Regex.Replace(value, @"\s+", " ");
}
之后:
string s = "current affairs ";
s = RemoveMultipleSpaces(s);
在这里使用正则表达式是一个好办法,
System.Text.RegularExpressions.Regex.Replace(input, @”\s+”, ” “);
这将删除所有空格字符,包括制表符、换行符等。
首先,您需要将整个字符串拆分,然后对每个项应用修剪。
string [] words = text.Split(' ');
text="";
forearch(string s in words){
text+=s.Trim();
}
//text should be ok at this time