将字符串转换为2D字符数组

时间:2014-11-23 22:52:10

标签: java arrays parsing

我正致力于开发一个自上而下的回溯解析器,但我却陷入了导入语法的困境。我的导师希望我们选择String[]并将其转换为char[][]

例如,教师会在命令行上输入一个语法a a S b X a a S a X a S a X,我的程序应该把它拿到2D格式中。

输入中的X应该在语法中表示|,因此生成的语法应该是

char[][] productions = new char[][] { {'a','a','S','b'},
                                      {'a','a','S','a'},
                                      {'a','S','a'},
                                      {'\0'} };

其中\0表示空字符串。我生成的以下代码char[4][],但我不确定如何为每个单独的生产制作数组。

    char[][] prod; int prodCount = 0, numProds = 0;
    String[] input = new String[] {"a","a","S","b","X","a","a","S","a","X",
                                    "a","S","a","X"};

    for(int i = 0; i < input.length; i++) {
        if(input[i] == "X") 
            prodCount++;
    }

    prod = new char[prodCount][];

    for(int i = 0; i < prod.length; i++) {
        for(int k = 0; k < input.length; k++) {
            if(input[k] == "X") {
                prod[i] = new char[numProds];
                numProds = 0; break;
            } else
                numProds++;
        }
    }

    for(int i = 0; i < prod.length; i++) {
        for(int j = 0; j < input.length; j++) {
            if(input[j] == "X") break;
            prod[i][j] = input[j].charAt(0);
        }
    }

编辑: 我已经研究了如何转换语法,但我仍然坚持如何在{2}数组中使用\0

    char[][] prod; int prodCount = 0, numProds = 0;
    String[] input = new String[] {"a","a","S","b","X",
                                   "a","a","S","a","X",
                                   "a","S","a","X"};

    for(int i = 0; i < input.length; i++) {
        if(input[i] == "X") 
            prodCount++;
    }

    prod = new char[prodCount][];

    int current = 0;
    for(int i = 0; i < input.length; i++) {
        if(input[i] == "X") {
            prod[current] = new char[numProds];
            current++; numProds = 0;
        } else
            numProds++;
    }

    int currentTerminal = 0; current = 0;
    for(int i = 0; i < input.length; i++) {
        if(input[i] == "X") {
            currentTerminal = 0;
            current++;
        }
        else {
            prod[current][currentTerminal] = input[i].charAt(0);
            currentTerminal++;
        }
    }

1 个答案:

答案 0 :(得分:0)

以下是一些可以满足您需求的简单代码:

    String grammar = "aaSbXaaSaXaSaX";
    String[] components = grammar.split("X");
    char[][] chars = new char[components.length + 1][];
    for (int i = 0; i < components.length; i++) {
        String component = components[i];
        chars[i] = component.toCharArray();
    }
    chars[components.length] = new char[] { '\0' };