将多个空间替换为单个空间? [英] Replace multiple space into single space?

查看:72
本文介绍了将多个空间替换为单个空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将多个空格替换为单个空格但新行文本无法替换。

新行文本就在该行上...?



例如

hi怎么样?

罚款.. !!



我想输出如下: -



嗨怎么样?

好​​...... !!



当我使用这段代码时



TextBox2.Text = Regex.Replace(str,{2,},);

输出如下:



hi怎么样?好...... !!

I'm trying replace multiple space into single space but new line text not to replace.
The new line text as it is on that line...?

e.g
hi How r u?
Fine..!!

I want the output as follows:-

hi How r u?
Fine..!!

When I use this code

TextBox2.Text = Regex.Replace(str, " {2,}", " ");
the output come as follows:

hi How r u?Fine..!!

推荐答案

string input = "your   input   string";
StringBuilder sb = new StringBuilder(input.Length);
bool spaceAdded = false;
for (int i=0; i<input.Length; i++)
{
    char c = input[i];
    if (c == ' ')
    {
        if (!spaceAdded)
        {
            sb.Append(' ');
            spaceAdded = true;
        }
    }
    else
    {
        sb.Append(c);
        spaceAdded = false;
    }
}
string output = sb.ToString();


尝试以下



http://stackoverflow.com/questions/206717/how-do-i-replace-multiple-spaces-with-a-single-space-in- c [ ^ ]


这篇关于将多个空间替换为单个空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆