我正在尝试将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
或任何其他字符串替换操作..