代码最简洁的是用正则string test = "aa bb cc dd"; string result = System.Text.RegularExpressions.Regex.Replace(test, @" +", " "); MessageBox.Show(result);讲求效率就这样string test = "aa bb cc dd"; int state = 0; StringBuilder temp = new StringBuilder(); for (int i = 0; i < test.Length; i++) { if (state == 0) { temp.Append(test[i]); if (test[i] == ' ') state = 1; } else { if (test[i] != ' ') { temp.Append(test[i]); state = 0; } } } string result = temp.ToString(); MessageBox.Show(result);
string result = System.Text.RegularExpressions.Regex.Replace(test, @" +", " ");
MessageBox.Show(result);讲求效率就这样string test = "aa bb cc dd";
int state = 0;
StringBuilder temp = new StringBuilder();
for (int i = 0; i < test.Length; i++)
{
if (state == 0)
{
temp.Append(test[i]);
if (test[i] == ' ')
state = 1;
}
else
{
if (test[i] != ' ')
{
temp.Append(test[i]);
state = 0;
}
}
}
string result = temp.ToString();
MessageBox.Show(result);