简体   繁体   中英

Convert string into two dimensional string array in Java

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

    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]]"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM