加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在字符串中冒号之间添加空格

发布时间:2020-12-15 19:41:01 所属栏目:百科 来源:网络整理
导读:预期的用户输入: Apple : 100Apple:100Apple: 100Apple :100Apple : 100Apple :100Apple: 100 预期结果: Apple : 100 冒号之间只需要一个空格: 码: string input = "Apple:100"; if (input.Contains(":")) { string firstPart = input.Split(':').First(
预期的用户输入:

Apple : 100

Apple:100

Apple: 100

Apple :100

Apple   :   100

Apple  :100

Apple:  100

预期结果:

Apple : 100

冒号之间只需要一个空格:

码:

string input = "Apple:100";

 if (input.Contains(":"))
 {
    string firstPart = input.Split(':').First();

    string lastPart = input.Split(':').Last();

    input = firstPart.Trim() + " : " + lastPart.Trim();
 }

上面的代码使用Linq,但是有没有更短或更高效的代码以及性能?

任何帮助,将不胜感激.

解决方法

你可以用这个衬垫:

input = string.Join(" : ",input.Split(':').Select(x => x.Trim()));

这比分裂两次更有效.但是,如果您想要更高效的解决方案,可以使用StringBuilder:

var builder = new StringBuilder(input.Length);
char? previousChar = null;
foreach (var ch in input)
{
    // don't add multiple whitespace
    if (ch == ' ' && previousChar == ch)
    {
        continue;
    }

     // add space before colon
     if (ch == ':' && previousChar != ' ')
     {
         builder.Append(' ');
     }

     // add space after colon
     if (previousChar == ':' && ch != ' ')
     {
          builder.Append(' ');
     }


    builder.Append(ch);
    previousChar = ch;
}

编辑:正如@Jimi的评论中提到的那样,foreach版本比LINQ慢.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读