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

sto*_*tom 3 .net c#

预期的用户输入:

Apple : 100

Apple:100

Apple: 100

Apple :100

Apple   :   100

Apple  :100

Apple:  100
Run Code Online (Sandbox Code Playgroud)

预期结果:

Apple : 100
Run Code Online (Sandbox Code Playgroud)

我在结肠之间只需要1个空格 :

码:

 string input = "Apple:100";

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

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

    input = firstPart.Trim() + " : " + lastPart.Trim();
 }
Run Code Online (Sandbox Code Playgroud)

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

任何帮助,将不胜感激.

Sel*_*enç 9

你可以用这个衬垫:

input = string.Join(" : ", input.Split(':').Select(x => x.Trim()));
Run Code Online (Sandbox Code Playgroud)

这比分裂两次更有效.但是,如果您想要更高效的解决方案,可以使用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;
}
Run Code Online (Sandbox Code Playgroud)

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


Pal*_*Due 5

你可以尝试这种老式的字符串操作:

int colonPos = input.IndexOf(':');
if (colonPos>-1)
{
    string s1 = input.Substring(0,colonPos).Trim();
    string s2 = input.Substring(colonPos+1, input.Length-colonPos-1).Trim();
    string result = $"{s1} : {s2}";
}
Run Code Online (Sandbox Code Playgroud)

是否更高性能,我不知道,赛马.

编辑:这个更快更简单(在0.132秒内完成100000次训练集迭代):

string result = input.Replace(" ","").Replace(":", " : ");
Run Code Online (Sandbox Code Playgroud)