用于解析字符串的Java方法

时间:2016-07-19 04:42:44

标签: java string java.util.scanner

我有一个输入字符串,如

{{1,2},{3,4},{5,6}}.

我想把数字读成二维数组,如

int[][] arr = {{1,2},{3,4},{5,6}}. 

有没有一种方法可以将此string转换为int[][]?感谢。

2 个答案:

答案 0 :(得分:0)

基本思想如下,您必须自己添加错误处理代码和更多逻辑计算数组大小。我只想展示如何分割字符串并制作int [][]array

    String test = "{{1,2},{3,4},{5,6}}"; 

    test = test.replace("{", "");
    test = test.replace("}", "");

    String []nums = test.split(",");
    int numIter = 0;

    int outerlength = nums.length/2;

    int [][]array = new int[outerlength][];

    for(int i=0; i<outerlength; i++){
        array[i] = new int[2]; 
        for(int j=0;j<2;j++){
            array[i][j] = Integer.parseInt(nums[numIter++]);
        }
    }
希望它有所帮助!

答案 1 :(得分:0)

我会使用动态存储(如List from Collections)寻求解决方案,然后在最后将其转换为固定的原始数组。

public static void main(String[] args) throws Exception {
    System.out.println(Arrays.deepToString(parse("{{1,2},{3,4},{5,6}}")));
}

private static int[][] parse(String input) {
    List<List<Integer>> output = new ArrayList<>();
    List<Integer> destination = null;

    Pattern pattern = Pattern.compile("[0-9]+|\\{|\\}");
    Matcher matcher = pattern.matcher(input);
    int level = 0;

    while (matcher.find()) {
        String token = matcher.group();
        if ("{".equals(token)) {
            if (level == 1) {
                destination = new ArrayList<Integer>();
                output.add(destination);
            }
            level++;
        } else if ("}".equals(token)) {
            level--;
        } else {
            destination.add(Integer.parseInt(token));
        }
    }
    int[][] array = new int[output.size()][];
    for (int i = 0; i < output.size(); i++) {
        List<Integer> each = output.get(i);
        array[i] = new int[each.size()];
        for (int k = 0; k < each.size(); k++) {
            array[i][k] = each.get(k);
        }
    }
    return array;
}

另一个替代方案是将{转换为[并将}转换为],然后您拥有JSON,只需使用您最喜欢的JSON解析器,此处我使用了GSON。< / p>

private static int[][] parse(String string) {
    JsonElement element = new JsonParser().parse(string.replace("{", "[").replace("}", "]"));
    JsonArray  obj = element.getAsJsonArray();
    int [][] output = new int[obj.size()][];
    for (int i = 0; i < obj.size(); i++) {
        JsonArray each = obj.get(i).getAsJsonArray();
        output[i] = new int[each.size()];
        for (int k = 0; k < each.size(); k++) {
            output[i][k] = each.get(k).getAsInt();
        }
    }
    return output;
}