algorithm - How can I parse a code string and build hierarchical array based on { and } in the string -
i have code-like string following:
a { bcd { ef { gh { } j } } k { lmn { op } qr { st } uv { wx } y } z } i wish parse string such can create hierarchical array code each tree gets created based on { , tree ends @ }.
the array like:
[ "a", "{", [ "bcd", "{", [ "ef", "{", [ "gh", "{", [ "i" ], "}", "j" ], "}" ], "}", "k", "{", [ "lmn", "{", [ "op" ], "}", "qr", "{", [ "st" ], "}", "uv", "{", [ "wx" ], "}", "y" ], "}", "z" ], "}" ] can 1 me in getting algo of this?
you can pass me code in of these languages java/c#/php/vb.net/javascript/actionscript.
if want write (c#):
class node { public string name { get; private set; } public ienumerable<node> children { get; private set; } public node(string name, ienumerable<node> children) { name = name; children = children; } } class parser { public node parse(string s) { return parse(s.split(new char[0], stringsplitoptions.removeemptyentries)); } public node parse(ienumerable<string> tokens) { using (var enumerator = tokens.getenumerator()) { enumerator.movenext(); // move first token return parse(enumerator); } } node parse(ienumerator<string> enumerator) { string name = enumerator.current; enumerator.movenext(); var children = new list<node>(); if (enumerator.current == "{") { enumerator.movenext(); while (enumerator.current != "}") { children.add(parse(enumerator)); } enumerator.movenext(); } return new node(name, children); } } this code doesn't check return value of movenext(), means produce weird results on invalid inputs (including possibility of infinite loop).
it requires tokens delimited whitespace. string a{b{c}} parsed 1 node name a{b{c}}.
creating special type node better using weakly-typed array (even if use weakly-typed language). , there no need include braces in result.
if want more complicated, recommend using parser library.
if string might long , you're reading file or network, might want use form of stream instead of ordinary string.
Comments
Post a Comment