[英]Parse such a String into a object structure using Java (GWT)
我試圖將GWT中的字符串解析為Object結構。 不幸的是我無法做到這一點。
示例字符串:
"(node1(node2(node3) (node4)) (node5))"
"node1"
有2 "node5"
: "node2"
和"node5"
"node2"
有2 "node4"
: "node3"
和"node4"
對象可以是“節點”,帶有子節點。 任何有關這方面的幫助將不勝感激。
我可以為您提供一個偽代碼。 我相信下面的算法會有效但如果你發現它有任何問題,請告訴我。
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
要跟蹤父母,可以使用堆棧。
我很無聊所以我把一些代碼敲了一下。
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();
}
}
你這樣稱呼它:
ObjectTree root = new ObjectTree();
root.parse("(node1(node2(node3) (node4)) (node5))");
System.out.println(root.toString());
得到:
(node1(node2(node3) (node4)) (node5)) :
.node1 :
. .node2 :
. . .node3 :
. . .node4 :
. .node5 :
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.