预期的用户输入:
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/