0

我正在尝试将IF语句转换如下

SET RESULT = IF(C>(X-2), (A+B), C) //IF C< X-2 return A+B otherwise return C

条件语句如下

SET RESULT = C>(X-2)?(A+B):C

我编写了一个代码,它扫描整个字符串并查看IF,(,. 当有超过 1 个IF语句时,我的算法不起作用,如下所示

SET RESULT = IF(C>(X-2), IF(P>C,2,3),C)

这是代码...

        string data = "SET RESULT=IF(C>(X-2), (A+B), C)";
        string output = string.Empty;

        int indexofIF = data.IndexOf("IF");
        int obCount = 0;
        int cbCount = 0;
        if (indexofIF > -1)
        {
            string script = data.Substring(indexOfIF, (data.Length-indexOfIF-1))
            for(int index=0; index<script.Length; index++)
            {
                int obIndex = data.IndexOf('(', index);
                if(obIndex>-1)
                    obCount++;
                int cbIndex = data.IndexOf(')', index);
                if(cbIndex>-1)
                    cbCount++;

                if(obCount==cbCount)//Found the end of If statement
                {
                    string tempData = data.Substring(0, index);
                    int count = tempData.Count(f => f == ',');//Get the number of occurences of ','
                    if (count == 2)//There are only 2 commas
                    {
                        int firstIndex = tempData.IndexOf(',');
                        int lastIndex = tempData.LastIndexOf(',');
                        string condtion = tempData.Substring(3, (firstIndex - 4));
                        string trueCond = tempData.Substring(firstIndex + 1, (lastIndex - firstIndex - 1));
                        string falseCond = tempData.Substring(lastIndex + 1, (index - lastIndex - 1));
                        output = condtion + "?" + trueCond + ":" + falseCond;

                    }
                    else //More than 2 commas
                    {

                    }
                }

            }

        }

我不确定这是否适用于复杂的场景。有没有更好的其他方法来做到这一点?也许使用regex或任何其他字符串替换操作..

4

1 回答 1

0

你在正确的轨道上。

我会:

  • 将每个字符读入一个小缓冲区
  • 评估缓冲区以查找单词“IF”
  • 设置一个标志,这样你就知道你在一个 IF 语句中
  • 清除缓冲区
  • 评估括号
  • 跟踪括号的打开/关闭
  • 执行任何附加逻辑(例如逗号解析)
  • 继续直到字符串的结尾

也许使用正则表达式或任何其他字符串替换操作..

(IF.*?(?=IF|$))分解出多个 IF 语句,但它不处理额外的解析,并要求输入数据遵循严格的结构。跟踪括号是棘手/不可能的(请参阅此答案的评论)并且更容易由状态机处理。

就个人而言,我喜欢逐字符解析的控制/灵活性。Code Mirror等工具使用这种方法来解析源代码。

A + B > C一旦成功提取了字符串的一部分(例如,将公式解构为它的部分),您可能会发现正则表达式很有用。

于 2012-04-23T01:26:26.053 回答