解析嵌套数组字符串

时间:2014-07-22 22:37:46

标签: java arrays string multidimensional-array

我试图在String中解析一个任意嵌套的数组,格式为:[3,[4,3],5],列表(列表,列表......)

我的例子,一旦解析,将是一个看起来像这样的列表:

List(3, List(4, 3), 5)

我写了一些代码(在此问题的先前编辑中),但我的草稿都没有奏效。我可以有一个示例实现还是一些伪代码?

1 个答案:

答案 0 :(得分:4)

将嵌套数组解析为这样的String非常简单:

Arrays.deepToString(array).replace(" ", "");

将此String转换为无限嵌套列表有点棘手。最简单的解决方案可能是使用递归:

/**
 * The following code is only for demonstration purposes.
 * It does neither do any validation on the input String 
 * nor work with more than one digit numbers.
 */

static int index = 0; // the position in the String

Object buildList(String nestedList) {
    List<Object> list = new ArrayList<>();

    while (index < nestedList.length()) {
        char c = nestedList.charAt(index++);

        if (c == '[') // add a sub-list via a recursive call
                list.add(buildList(nestedList));
        else if (c == ']') // stop building the list
                 break;
        else if (c == ',') {} // do nothing
        else // add an element to the list
            list.add(c);
    }

    return list;
}

示例电话:

System.out.println(buildList("[3,[4,3],5]")); // prints [3, [4, 3], 5]


注意:

即使上面的代码做了(至少我认为)你想要实现的东西,但在实践中使用这样的数据结构可能并不明智,因为对嵌套列表的访问非常复杂并涉及到一些铸造。

更好的解决方案可能是使用某种树数据结构,其中每个节点都有一个值列表,包括指向其他​​节点的链接。 (见:http://en.wikipedia.org/wiki/Tree_(data_structure)