0

I have a input string like

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

I want to read the numbers into an two dimensional array like

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

Is there a good way to convert this string into int[][] ? Thanks.

geekintown
  • 119
  • 1
  • 10
  • 1
    Possible duplicate of [Converting String to Int in Java?](http://stackoverflow.com/questions/5585779/converting-string-to-int-in-java) – Franckentien Jul 19 '16 at 04:47
  • it is not just to convert String into Int but to read from the format as specified which is what i am looking for. thanks. – geekintown Jul 19 '16 at 05:06
  • In this case you can look at [regex](http://stackoverflow.com/a/14584318/6114929) and this for [save many value](http://stackoverflow.com/a/6401027/6114929) – Franckentien Jul 19 '16 at 05:20

2 Answers2

0

The basic idea is as follows, you will have to add error handling code and more logical calculation of array size yourself. I just wanted to display how to split the string and make 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++]);
        }
    }

hope it helps!

Mrunal Pagnis
  • 801
  • 1
  • 9
  • 26
0

I'd go for solution using dynamic storage such as List from Collections, and then convert this to fixed primitive array at the end.

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;
}

Another alternative would be translate { to [ and } to ], then you have JSON, just use your favourite JSON parser, here I used GSON.

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;
}
Adam
  • 35,919
  • 9
  • 100
  • 137
  • Thanks Adam. The first solution proposed by you is not working for input array like `{{1,44},{3,4},{5,6}}` – geekintown Jul 19 '16 at 08:28
  • @geekintown Fixed answer to user Pattern instead of Scanner, in hindsight either than trying to use delimiters... which was only matching single characters – Adam Jul 19 '16 at 09:41