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
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.
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.
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.
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.
Arrays.deepToString
and Arrays.deepEquals
for multidimensional arraysIf 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]]"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With