简体   繁体   中英

How do I convert a String into a 2D array

I have to define a method called getDistance. That takes the following string: 0,900,1500<>900,0,1250<>1500,1250,0 and returns a 2d array with the all the distances. The distances are separated by "<>" symbol and they are separated into each column by ",".

I know I need to use String.split method. I know splitting by the commmas will give me the columns and splitting it by the "<>" will give me the rows.

   public static int[][] getDistance(String array) {
        String[]row= array.split(",");
        String[][] distance;
        int[][] ctyCoord = new int[3][3];
        for (int k = 0; k < row.length; k++) {
            distance[k][]=row[k].split("<>");
                ctyCoord[k][j] = Integer.parseInt(str[j]);
            }
        return ctyCoord;

I think you should first split along the rows and then the colums. I would also scale the outer array with the number of distances.

public static int[][] getDistance(String array) {
    String[] rows = array.split("<>");
    int[][] out = new int[rows.length][3];
    for (int i = 0; i < rows.length, i++) {
        String values = rows[i].split(",");
        for (int j = 0; j < 3, j++) {
            out[i][j] = Integer.valueOf(values[j]);
        }
    }
    return out;

This is a working dynamic solution:

public static int[][] getDistance(String array) {

        String[] rows = array.split("<>");
        int[][] _2d = null;

        // let us take the column size now, because we already got the row size
        if (rows.length > 0) {
            String[] cols = rows[0].split(",");
            _2d = new int[rows.length][cols.length];
        }

        for (int i = 0; i < rows.length; i++) {
            String[] cols = rows[i].split(",");
            for (int j = 0; j < cols.length; j++) {
                _2d[i][j] = Integer.parseInt(cols[j]);
            }
        }
        return _2d;

    }

Let's test it:

public static void main(String[] args) {
        String given = "0,900,1500<>900,0,1250<>1500,1250,0";

        int[][] ok = getDistance(given);
        for (int i = 0; i < ok.length; i++) {
            for (int j = 0; j < ok[0].length; j++) {
                int k = ok[i][j];
                System.out.print(k + " ");
            }
            System.out.println();
        }
    }

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