当前位置:编程学习 > C#/ASP.NET >>

求将多个连续空格替换为一个空格的方法,如"aa bb cc dd"

求将多个连续空格替换为一个空格的方法,如"aa        bb   cc               dd"

最终结果:aa bb cc dd --------------------编程问答-------------------- .Trim() --------------------编程问答-------------------- .replace("  "," "); --------------------编程问答--------------------

 str = System.Text.RegularExpressions.Regex.Replace(str, "\\s+", " ");
--------------------编程问答-------------------- 代码最简洁的是用正则

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);
--------------------编程问答-------------------- 学习了。 --------------------编程问答--------------------   --------------------编程问答-------------------- 支持4楼 --------------------编程问答-------------------- csdn不同凡响啊
补充:.NET技术 ,  ASP.NET
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,