首页 > 解决方案 > 有效地拆分格式为“{ {}, {}, ...}”的字符串

问题描述

我有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# 非常陌生,任何帮助将不胜感激。

标签: c#splitstring-parsing

解决方案


不要专注于 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 个分配”。


推荐阅读