11

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?

6
  • Which line is line 94? Commented Apr 9, 2015 at 18:51
  • This line matrix[r1++] = row1.split(","); Commented Apr 9, 2015 at 18:53
  • Did you look up an ArrayIndexOutOfBoundsException to make an effort to understand what it is and why it happens? Did you use your debugger to step through the code? Commented Apr 9, 2015 at 18:54
  • Ok i will try to search that Commented Apr 9, 2015 at 18:56
  • I think your trying to alter the wrong variable here matrix[r1++] = row1.split(",");. Shouldn't it be matrix1? Try using variable names which do a little bit in explaining what the variables role is. Commented Apr 9, 2015 at 18:59

5 Answers 5

9

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

Sign up to request clarification or add additional context in comments.

1 Comment

ok. But this line : s1[i]=s1[i].trim(); just make result more beautifull, right?
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);

Comments

1

Try this...

String s="[[4, 2, 2, 4], [3, 4, 5, 6], [6, 7, 8, 9], [3, 2, 1, 4]]";

// Split on this delimiter
String[] rows = s.split("], \\[");
for (int i = 0; i < rows.length; i++) {
    // Remove any beginning and ending braces and any white spaces
    rows[i] = rows[i].replace("[[", "").replace("]]", "").replaceAll(" ", "");
}

// Get the number of columns in a row
int numberOfColumns = rows[0].split(",").length;

// Setup your matrix
String[][] matrix = new String[rows.length][numberOfColumns];

// Populate your matrix
for (int i = 0; i < rows.length; i++) {
    matrix[i] = rows[i].split(",");
}
// Display your matrix
System.out.println(Arrays.deepToString(matrix));

Results:

enter image description here

Comments

0

This just doesn't add the comma's at the end of the line:

    String s = "[[4, 2, 2, 4], [3, 4, 5, 6], [6, 7, 8, 9], [3, 2, 1, 4]]";
    for (String l: s.split("\\]\\s*,\\s*\\[")) {
        l = l.replaceAll("\\[", "").replaceAll("\\]", "");
        System.out.println("{" + l + "}");
    }

Comments

0

Assuming that the input string will always be in that format, with 4 integers between each bracket, I think the best way to do it would simply be to use a Scanner object and it's nextInt() method which will ignore the brackets and comma's and just find the numbers. Then put them into a 2d array like how you would with a loop.

It kinda gets rid of all the fun you were having with removing the brackets though, so it's not really better in terms of making an exercise out of this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.