Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
add comment

1 Answer

up vote 10 down vote accepted
    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]]"
share|improve this answer
 
Thanks alot!! it worked!! –  kaibuki May 7 '10 at 7:33
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.