c# - 在字符串中的冒号之间添加空格
问题描述
预期的用户输入:
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()));
这比拆分两次更有效。但是,如果您想要更有效的解决方案,您可以使用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# - 在 WPF XAML 中使用 MVVM 而不是 MultiValueConverter
- javascript - 如何让屏幕阅读器在 Angular 或任何单页应用程序中加载新页面时通知?
- python - python 3.7单行理解
- javascript - React - useState 仅影响最后一个属性值
- sql - 检查 postgres 表中列的唯一性
- c++ - 如何在内存中的数据缓冲区上使用常规 std::basic_istream::read、std::basic_ostream::write?
- linux - 如何使用 bash 同时运行多个可执行代码?
- java - 创建基于自定义生成器/迭代器方法的流
- virtual - Vmware 工作站 15 上的 RDP
- amazon-web-services - AWS Cloudformation:“Lambda 函数的权限无效”出了什么问题?