嘿伙计们,我有这样的字符串
“THIS_的 ___ is_a _ _string。”
,我想把所有多个空格都变成一个。 C#中是否有任何可以执行此操作的功能?
谢谢
答案 0 :(得分:11)
var s = "This is a string with multiple white space";
Regex.Replace(s, @"\s+", " "); // "This is a string with multiple white space"
答案 1 :(得分:5)
Regex r = new Regex(@"\s+");
string stripped = r.Replace("Too many spaces", " ");
答案 2 :(得分:3)
这是没有正则表达式的好方法。有了Linq。
var astring = "This is a string with to many spaces.";
astring = string.Join(" ", astring.Split(' ').Where(m => m != string.Empty));
输出"This is a string with to many spaces"
答案 3 :(得分:2)
此页面上的正则表达式示例可能不错,但这是一个没有正则表达式的解决方案:
string myString = "This is a string.";
string myNewString = "";
char previousChar = ' ';
foreach(char c in myString)
{
if (!(previousChar == ' ' && c == ' '))
myNewString += c;
previousChar = c;
}