Convert string to two-dimensional array of strings in Java

I like to convert the 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 tried using the split("") method, but there is still no solution :(

Thanks..

Kai

+7
java string arrays
source share
1 answer
  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]]" 
+21
source share

All Articles