c# - 有效地拆分格式为“{ {}, {}, ...}”的字符串
问题描述
我有string
以下格式。
string instance = "{112,This is the first day 23/12/2009},{132,This is the second day 24/12/2009}"
private void parsestring(string input)
{
string[] tokens = input.Split(','); // I thought this would split on the , seperating the {}
foreach (string item in tokens) // but that doesn't seem to be what it is doing
{
Console.WriteLine(item);
}
}
我想要的输出应该是这样的:
112,This is the first day 23/12/2009
132,This is the second day 24/12/2009
但目前,我得到以下一个:
{112
This is the first day 23/12/2009
{132
This is the second day 24/12/2009
我对 C# 非常陌生,任何帮助将不胜感激。
解决方案
不要专注于 Split() 是解决方案!没有它,这是一件很容易解析的事情。正则表达式的答案可能也可以,但我想就原始效率而言,制作“解析器”可以解决问题。
IEnumerable<string> Parse(string input)
{
var results = new List<string>();
int startIndex = 0;
int currentIndex = 0;
while (currentIndex < input.Length)
{
var currentChar = input[currentIndex];
if (currentChar == '{')
{
startIndex = currentIndex + 1;
}
else if (currentChar == '}')
{
int endIndex = currentIndex - 1;
int length = endIndex - startIndex + 1;
results.Add(input.Substring(startIndex, length));
}
currentIndex++;
}
return results;
}
所以它的线路并不短。它迭代一次,每个“结果”只执行一次分配。稍微调整一下,我可能可以制作一个带有索引类型的 C#8 版本来减少分配?这可能已经足够好了。
您可能会花一整天时间弄清楚如何理解正则表达式,但这很简单:
- 扫描每个字符。
- 如果找到
{
,请注意下一个字符是结果的开始。 - 如果您找到
}
,请考虑从最后注明的“开始”到此字符之前的索引的所有内容作为“结果”。
这不会捕获不匹配的括号,并且可能会为“}}{”之类的字符串抛出异常。你没有要求处理这些案件,但改进这种逻辑以抓住它并为此尖叫或恢复并不难。
例如,您可以在找到startIndex
时重置为 -1 之类}
的值。从那里,你可以推断你是否{
在 startIndex != -1 时找到了“{{”。如果你发现}
startIndex == -1,你可以推断,你已经找到了“}}”。如果你在 startIndex < -1 的情况下退出循环,那是一个{
没有关闭的开头}
。这将字符串 "}whoops" 保留为未发现的情况,但可以通过初始化startIndex
为 -2 并专门检查它来处理它。用正则表达式来做,你会头疼的。
我建议这样做的主要原因是您说“有效”。icepickle 的解决方案很好,但Split()
每个令牌分配一次,然后为每个TrimX()
调用执行分配。这不是“有效的”。那是“n + 2 个分配”。
推荐阅读
- c# - WPF XAML 文件中的 ObjectDataProvider.ConstructorParameters 疑难解答
- python - 在 pandas 数据框中从“年-月-日”格式中删除年份
- python - python - 将geopandas与python一起使用时如何使形状文件中的线条更粗?
- r - 在 r 中的组条件下从另一个数据帧中找到最接近的对值
- ruby-on-rails - Rails 5 中单个页面上的多个 Ajax 链接
- mongodb - 查询此文档的正确方法是什么?(如果索引正确)
- javascript - 如何正确地将来自多个嵌套查询的数据映射到所需的对象。反应/火力基地
- sql - 是否有一个 sql 函数可以查看输出并判断一个单元格和它上面的单元格是否相等?
- c - 是否有将读/写功能标记为线程安全功能的官方文档?
- visual-studio-code - VS Code 状态栏左侧的 >< 图标是什么?