【发布时间】:2014-05-16 11:19:58
【问题描述】:
我正在构建由非常自定义的语言驱动的自定义资源提供程序。为此,我必须从自定义表达式创建树数据结构。让我解释一下:
f1(f2,f3,f6(f4),f5)
上面是我的自定义表达式的示例,我想从中构建树。根 - f1,有孩子:f2,f3,f4,f5。但是f4 也有自己的孩子。
我已经为这个问题编写了解决方案,但我想找到更好的方法来实现这个目标。
class Node
{
public string val;
public List<Node> child = new List<Node>();
}
private Node parseInput(string input, int index)
{
string nodeName = findToken(input,ref index);
Node tmp = new Node() { val = nodeName };
tmp.child = expandNodes(input, ref index);
return tmp;
}
private List<Node> expandNodes(string input, ref int index)
{
List<Node> res = new List<Node>();
while (!char.IsLetterOrDigit(input[index++]) && index < input.Length) ;
index--;
while (index < input.Length)
{
if (checkNext(input, index, ')'))
{
while (!char.IsLetterOrDigit(input[index++]) && index < input.Length) ;
index--;
return res;
}
Node tmp = new Node() { val = findToken(input,ref index) };
if (checkNext(input, index, '('))
{
tmp.child = expandNodes(input, ref index);
}
res.Add(tmp);
}
return res;
}
private bool checkNext(string s, int index, char desiredChar)
{
string vc = "" + s[index];
while (index < s.Length && !char.IsLetterOrDigit(s[index]))
{
char chr = s[index];
if (chr == desiredChar)
{
return true;
}
index++;
}
return false;
}
private string findToken(string s, ref int index)
{
string res = null;
while (!char.IsLetterOrDigit(s[index++]) && index < s.Length) ;
index--;
while (index < s.Length && char.IsLetterOrDigit(s[index]))
{
res += s[index];
index++;
}
return res;
}
【问题讨论】:
-
你在寻找什么样的“更好的方法”?
-
更高效、更优雅的算法
标签: c# parsing expression hierarchical