I have a String:
1,3,4,5,
1,4,5,0,
2,5,3,8,
That I want to store in a variable matrix (int[][]
). What is the best way to accomplish this? Should I use the String
class' methods? Or should I use a Regex
?
First (by String.split(..)
) split on newline, then split the items of each of the resultant array on ,
. Then parse each using Integer.parseInt(..)
String input = "1,3,4,5,\n1,4,5,0,\n2,5,3,8,";
String[] str1 = input.split("\n");
int[][] matrix = new int[str1.length][];
for (int i = 0; i < matrix.length; i++) {
String[] str2 = str1[i].split(",");
matrix[i] = new int[str2.length];
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = Integer.parseInt(str2[j]);
}
}