我有很多看起来像这样的字符串:
current affairs
我希望将字符串设为:
current affairs
我尝试使用Trim()
,但它不会完成这项工作
答案 0 :(得分:11)
正则表达式可以完成这项工作
string_text = Regex.Replace(string_text, @"\s+", " ");
答案 1 :(得分:6)
您可以使用正则表达式,请参阅Regex.Replace
:
var normalizedString = Regex.Replace(myString, " +", " ");
如果您想要所有类型的空白,请使用@"\s+"
代替仅处理空格的" +"
。
var normalizedString = Regex.Replace(myString, @"\s+", " ");
答案 2 :(得分:0)
使用正则表达式。
yourString= Regex.Replace(yourString, @"\s+", " ");
答案 3 :(得分:0)
您可以使用正则表达式:
public string RemoveMultipleSpaces(string s)
{
return Regex.Replace(value, @"\s+", " ");
}
后:
string s = "current affairs ";
s = RemoveMultipleSpaces(s);
答案 4 :(得分:0)
在这里使用Regex,
System.Text.RegularExpressions.Regex.Replace(input, @”\s+”, ” “);
这将删除所有空格字符,包括制表符,换行符等。
答案 5 :(得分:-1)
首先,您需要拆分整个字符串,然后对每个项目应用修剪。
string [] words = text.Split(' ');
text="";
forearch(string s in words){
text+=s.Trim();
}
//text should be ok at this time