[英]Parse such a String into a object structure using Java (GWT)
I am trying to parse an string in GWT to an Object structure. 我试图将GWT中的字符串解析为Object结构。 Unfortunately I am not able to do it.
不幸的是我无法做到这一点。
Example string: 示例字符串:
"(node1(node2(node3) (node4)) (node5))"
"node1"
has 2 children: "node2"
and "node5"
"node1"
有2 "node5"
: "node2"
和"node5"
"node2"
has 2 children: "node3"
and "node4"
"node2"
有2 "node4"
: "node3"
和"node4"
Object can be "node", with children. 对象可以是“节点”,带有子节点。 Any help on this will be greatly appreciated.
任何有关这方面的帮助将不胜感激。
I can provide you with a pseudo-code. 我可以为您提供一个伪代码。 I believe the following algorithm will work but please let me know if you spot anything wrong with it.
我相信下面的算法会有效但如果你发现它有任何问题,请告诉我。
Create a root node called nodeRoot.
current_node = nodeRoot
For each char in the string:
if the char is '('
add a child node to current_node
parse the string (after the '(' char) to fetch the name of the node
current_node = the newly added child node
else if the char is ')'
current_node = parent of current_node
To keep track of parents, you can use a stack. 要跟踪父母,可以使用堆栈。
I'm pretty bored so I knocked together some code. 我很无聊所以我把一些代码敲了一下。
private static class ObjectTree {
private Set<ObjectTree> children = new LinkedHashSet();
private ObjectTree parent = null;
private String text = null;
private int level = 0;
public ObjectTree() {
this(null);
}
public ObjectTree(ObjectTree parent) {
this(parent, 0);
}
public ObjectTree(ObjectTree parent, int level) {
this.parent = parent;
this.level = level;
}
public void addChild(ObjectTree child) {
children.add(child);
}
public void parse(String s) {
int ix = s.indexOf("(");
if (ix > 0)
text = s.substring(0, ix);
else if (ix <= 0)
text = s;
int iy = ix + 1;
int count = 1;
if (ix == -1)
return;
while (iy < s.length()) {
if (s.charAt(iy) == ')')
count--;
else if (s.charAt(iy) == '(')
count++;
if (count == 0) {
String newString = s.substring(ix + 1, iy);
ObjectTree newChild = new ObjectTree(this, level + 1);
addChild(newChild);
newChild.parse(newString);
ix = s.indexOf('(', iy);
count++;
iy = ix;
}
iy++;
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(StringUtils.repeat("\t.", level)).append(text).append(" :\n");
for (ObjectTree child : children) {
sb.append(StringUtils.repeat("\t", level)).append("\t").append(child.toString()).append("\n");
}
if (!children.isEmpty())
sb.append("\n");
return sb.toString();
}
}
You call it like so: 你这样称呼它:
ObjectTree root = new ObjectTree();
root.parse("(node1(node2(node3) (node4)) (node5))");
System.out.println(root.toString());
And get: 得到:
(node1(node2(node3) (node4)) (node5)) :
.node1 :
. .node2 :
. . .node3 :
. . .node4 :
. .node5 :
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.