I try to convert this string
s=[[4, 2, 2, 4], [3, 4, 5, 6], [6, 7, 8, 9], [3, 2, 1, 4]]
into a two dimensional array like this
{4, 2, 2, 4},
{3, 4, 5, 6},
{6, 7, 8,9},
{3, 2, 1, 4}
by use this code
int e=s.replaceAll("\\[", "").replaceAll(" ","").replaceAll("],","]").length();
String[] rows1 = s.replaceAll("\\[", "").replaceAll(" ","").replaceAll("],","]").substring(0, e-2).split("]");
String[][] matrix1 = new String[4][4];
int r1 = 0;
for (String row1 : rows1) {
matrix[r1++] = row1.split(",");
}
System.out.println(Arrays.deepToString(matrix1));
But is have problem like this
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at test.main(test.java:94)
Can you help me find a solution?
I think this code will help you. Read the all comments carefully.
String s="[[4, 2, 2, 4], [3, 4, 5, 6], [6, 7, 8, 9], [3, 2, 1, 4]]";
s=s.replace("[","");//replacing all [ to ""
s=s.substring(0,s.length()-2);//ignoring last two ]]
String s1[]=s.split("],");//separating all by "],"
String my_matrics[][] = new String[s1.length][s1.length];//declaring two dimensional matrix for input
for(int i=0;i<s1.length;i++){
s1[i]=s1[i].trim();//ignoring all extra space if the string s1[i] has
String single_int[]=s1[i].split(", ");//separating integers by ", "
for(int j=0;j<single_int.length;j++){
my_matrics[i][j]=single_int[j];//adding single values
}
}
//printing result
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(my_matrics[i][j]+" ");
}
System.out.println("");
}
[[4, 2, 2, 4], [3, 4, 5, 6], [6, 7, 8, 9], [3, 2, 1, 4]]
Logic: 1) replacing all [ to "" now I have-> 4, 2, 2, 4], 3, 4, 5, 6], 6, 7, 8, 9], 3, 2, 1, 4]]
2) Separating all by "]," now I have->
A) 4, 2, 2, 4
B) 3, 4, 5, 6
c) 6, 7, 8, 9
d) 3, 2, 1, 4
3) Separating A B C D by ", " now I have->
A) a) 4 b) 2 c) 2 d) 4
B) a) 3 b) 4 c) 5 d) 6
c) a) 6 b) 7 c) 8 d) 9
d) a) 3 b) 2 c) 1 d) 4
Solution using Java streams:
String[][] arr = Arrays.stream(str.substring(2, str.length() - 2).split("\\],\\["))
.map(e -> Arrays.stream(e.split("\\s*,\\s*"))
.toArray(String[]::new)).toArray(String[][]::new);
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