user3451500
user3451500

Reputation: 29

How to convert the string into a fixed int 2D array(special case)?

Here is my string 100000000000000000000000000000000000000000000000000000000000

a string combined with 60 1/0.

I want to put it into a int Array[6][10]. I tried to add "," between each row, but it failed

String data = "1000000000,0000000000,0000000000,0000000000,0000000000,0000000000";
String[] rows = data.split(",");

String[][] matrix = new String[rows.length][];
int r = 0; 
for (String row : rows) { 
   matrix[r++] = row.split("\\|"); 
}
System.out.print(matrix);

Please help and solve this problem, thank you!

Upvotes: 2

Views: 65

Answers (1)

merlin2011
merlin2011

Reputation: 75545

Here's a very straightforward solution that does not require splitting on regex or inserting commas:

String input = "100000000000000000000000000000000000000000000000000000000000";
int[][] matrix = new int[6][10];
for (int i = 0; i < 6; i++)
  for (int j = 0; j < 10; j++)
    matrix[i][j] = Integer.parseInt(input.charAt(i * 10 + j) + "");

Upvotes: 2

Related Questions