你可以用这个衬垫:
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慢.