Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 478
Adil Bhatty Avatar asked May 07 '10 06:05

Adil Bhatty


People also ask

How do I convert a String to a 2D array?

To convert a string into a two-dimensional array, you can first use the Split() method to split the string into Int-type values and store them in a one-dimensional array. Then read the values in a one-dimensional array and store them in a two-dimensional array.

Can you make a 2D array of objects in Java?

Java Two Dimensional Array of Objects We can declare a 2D array of objects in the following manner: ClassName[][] ArrayName; This syntax declares a two-dimensional array having the name ArrayName that can store the objects of class ClassName in tabular form.

Can you create a 2 dimensional array with different types?

You can have multiple datatypes; String, double, int, and other object types within a single element of the arrray, ie objArray[0] can contain as many different data types as you need. Using a 2-D array has absolutely no affect on the output, but how the data is allocated.


1 Answers

    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

  • 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-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]]"
like image 157
polygenelubricants Avatar answered Oct 23 '22 03:10

polygenelubricants