I'm building custom resource provider driven by very custom language. In order to do that I have to create tree data structure from custom expression. Let me explain:
f1(f2,f3,f6(f4),f5)
Above, is example of my custom expression , from which I want to build tree. Root - f1, has children : f2, f3, f4, f5. But f4 also has it's own children.
I've written solution for this problem, but I want to find better way to achieve this goal.
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;
}
