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 simple, except that String.split accepts a regular expression, so the metacharacter | shielding is required.
see also
- Regular expressions and escaping special characters
- Java Arrays.equals () returns false for two-dimensional arrays.
- Use
Arrays.deepToString and Arrays.deepEquals for multidimensional arrays
Alternative
If you know how many rows and columns there will be, you can pre-select String[][] and use 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
source share