简体   繁体   中英

Convert a 1D string to a 2D array of Integers

I have a string and I want to convert it to a 2D array of integers. This is what I am doing:

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

//Putting each element into an array of strings

String stringArray[]=string1.split("~");

//Determining the number of columns for the 2D array

int countints=0;
Scanner ins = new Scanner(stringArray[0]);
while (ins.hasNext()){
    countints+=1;
    ins.next();
}

//converting into an array of integers

int intArray[][]=new int[stringArray.length][countints];

Here I'm stuck as how to parse each integer into the 2D array.

Once you have initialized the 2D array, you need to parse each element in stringArray by getting rid of trailing and leading '[', ']' bracket pairs and splitting it with "," and parse each element of the split string into Integer and put that int value to the given 2d array at correct postion.

EDIT: WORKING SOLUTION

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

    String stringArray[]=string1.split("~");

    int countints = stringArray[0].substring(1, stringArray[0].length()-1).split(",").length;

    int intArray[][]=new int[stringArray.length][countints];

    for(int i = 0; i < stringArray.length; i++)
    {
       String s = stringArray[i].substring(1, stringArray[i].length()-1);
       String[] elementArray = s.split(",");
       for(int j = 0; j < elementArray.length; j++)
       {
           int val = Integer.parseInt(elementArray[j]);
           intArray[i][j] = val;
       }
    }
String string1="[1,2,3]~[4,5,6]~[7,8,9]~";
String string2 = string1.replace("[","").replace("]","");

for(int i = 0; i < stringArray.length; i++)
{
   String s = stringArray[i].substring(1, stringArray[i].length()-1);
   String[] elementArray = s.split(",");
   for(int j = 0; j < elementArray.length; j++)
   {
       int val = Integer.parseInt(elementArray[j]);
       intArray[i][j] = val;
   }
}

For a totally dynamic array:

String string1 = "[1,2,3]~[4,5,6]~[7,8,9]~";
String[] lines = string1.split("(^|~)\\[");
int[][] array = new int[lines.length][0];

Pattern pat = Pattern.compile("\\d+");

int lineIndex = 0;
for (String line : lines) {

    //if the row size is dynamic
    Matcher m1 = pat.matcher(line);
    int rowSize = 0;
    while (m1.find())
        rowSize++;

    array[lineIndex] = new int[rowSize];

    int colIndex = 0;
    Matcher m2 = pat.matcher(line);
    while (m2.find()) {
        array[lineIndex][colIndex++] = Integer.parseInt(m2.group());
    }
    lineIndex++;
}

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

It prints:

1 2 3 
4 5 6 
7 8 9 

Here is a clean solution that works. I started working on it before I got through all of the other answers, so my apologies if it doesn't meaningfully add to what is already here:

public class SO {
    public static int[][] parse(String input) {
        String[] rows = input.split("~");
        int[][] ints = new int[rows.length][];
        int j = 0;
        for(String row : rows) {
            String[] cols = row.substring(1, row.length()-1).split(",");
            int k = 0;
            ints[j] = new int[cols.length];
            for(String col : cols) {
                ints[j][k++] = Integer.parseInt(col);
            }
            j++;
        }

        return ints;
    }

    public static void main(String[] args) {
        for(int[] row : parse("[1,2,3]~[4,5,6]~[7,8,9]~")) {
            for(int col : row) {
                System.out.print(","+col);
            }
            System.out.println();
        }
    }
}

This produces the output:

,1,2,3
,4,5,6
,7,8,9

As for error checking you should decide upfront how you want to handle error checking, As this is written a single invalid int will throw an exception, which I think is the correct behavior. Malformed rows on the other hand might give unpredictable output (which I would say is wrong if the input has even the slightest potential to be malformed).

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