views:

376

answers:

1

Hi guys,

I like to convert string for example :

String data = "1|apple,2|ball,3|cat";

into a two dimensional array like this

{{1,apple},{2,ball},{3,cat}}

I have tried using the split("") method but still no solution :(

Thanks..

Kai

+7  A: 
    String data = "1|apple,2|ball,3|cat";
    String[] rows = data.split(",");

    String[][] matrix = new String[rows.length][]; 
    int r = 0;
    for (String row : rows) {
        matrix[r++] = row.split("\\|");
    }

    System.out.println(matrix[1][1]);
    // prints "ball"

    System.out.println(Arrays.deepToString(matrix));
    // prints "[[1, apple], [2, ball], [3, cat]]"

Pretty straightforward except that String.split takes regex, so metacharacter | needs escaping.

See also


Alternative

If you know how many rows and columns there will be, you can pre-allocate a String[][] and use a Scanner as follows:

    Scanner sc = new Scanner(data).useDelimiter("[,|]");
    final int M = 3;
    final int N = 2;
    String[][] matrix = new String[M][N];
    for (int r = 0; r < M; r++) {
        for (int c = 0; c < N; c++) {
            matrix[r][c] = sc.next();
        }
    }
    System.out.println(Arrays.deepToString(matrix));
    // prints "[[1, apple], [2, ball], [3, cat]]"
polygenelubricants
Thanks alot!!it worked!!
kaibuki