首页 > 解决方案 > 在字符串中的冒号之间添加空格

问题描述

预期的用户输入:

Apple : 100

Apple:100

Apple: 100

Apple :100

Apple   :   100

Apple  :100

Apple:  100

预期结果:

Apple : 100

我只需要冒号之间的 1 个空格:

代码:

 string input = "Apple:100";

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

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

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

上面的代码正在使用Linq,但是有没有考虑到性能的更短或更高效的代码?

任何帮助,将不胜感激。

标签: c#.net

解决方案


您可以使用这一衬里:

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 慢。


推荐阅读