简体   繁体   中英

How do I convert a String to an 2D Array of ints?

Currently I have a String called x that displays the following

100
000
000

How do I convert it into an nxn, int[][] array called board ? The array contents should look like how its printed above. However, the array must be initialized depending on the rows / columns of the String. In the example above, it should be a 3x3 array.


I'm not sure how to start. The first problem I have is iterating through the String and counting how many "rows" / "columns" are in the String,

In addition to writing the contents in the correct order. Here is what I have attempted so far...

for (int i = 0; i < x.length(); i++)
{
    char c = x.charAt(i);
    board[i][] = c;
}

I assume that your string stored in Java looks like String str = "100\r\n000\r\n000"; , then you can convert it to a 2D array as follows:

Code snippet

String str = "100\r\n000\r\n000";
System.out.println(str);

String[] str1dArray = str.split("\r\n");
String[][] str2dArray = new String[str1dArray.length][str1dArray[0].length()];
for (int i = 0; i < str1dArray.length; i++) {
    str2dArray[i] = str1dArray[i].split("");

    System.out.println(Arrays.toString(str2dArray[i]));
}

Console output

100
000
000
[1, 0, 0]
[0, 0, 0]
[0, 0, 0]

Updated

Following code snippet shows how to convert the string to a 2D integer array with Lambda expression (since Java 8).

int[][] str2dArray = new int[str1dArray.length][str1dArray[0].length()];
for (int i = 0; i < str1dArray.length; i++) {
    str2dArray[i] = Arrays.stream(str1dArray[i].split("")).mapToInt(Integer::parseInt).toArray();

    // This also works without using Lambda expression
    /*
    for (int j = 0; j < str1dArray[i].length(); j++) {
        str2dArray[i][j] = Integer.parseInt(String.valueOf(str1dArray[i].charAt(j)));
    }
    */
    System.out.println(Arrays.toString(str2dArray[i]));
}

With your data you will have only the first row, you need more data.

String a = "100\n" +
           "000\n" +
           "000";
String matriz[][] = {a.split("\n")};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM