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

标签 c# .net

预期的用户输入:

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 工作,但是是否有考虑到性能的更短或更高效的代码?

如有任何帮助,我们将不胜感激。

最佳答案

你可以使用这个衬垫:

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

这比 split 两次更有效率。但是,如果您想要更高效的解决方案,可以使用 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 慢。

关于c# - 在字符串中的冒号之间添加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52078952/

相关文章:

c# - 使用 OneDrive API 的正确方法是什么?

.net - 如何强制使用 xsi :type attribute?

.net - ComboBox 数据源和 application.setting 问题

c# - 选择什么 .NET 版本以避免安装另一个框架?

C# HtmlAgilityPack HtmlDocument() LoadHtml编码

C# SetForegroundWindow 不工作

.net - 替换系统命名空间中的类

c# - 如何迭代数组/集合/列表中的 "between"项?

c# - 在 cshtml 编辑器中触发 IntelliSense 时,Visual Studio 2015(更新 1)崩溃

c# - 尝试检测 iOS 手机是否处于静音状态时遇到问题?