Most elegant way to turn a String into a nested Array

I get a String of the format
<num-num-num><num-num-num><num-num-num>. I want to turn this into a nested Array of Ints with each Array being the content between the <>.

This is what I got so far:

            String parameter = args[1];
            // split the string into an array of strings at >
            String[] splitString = parameter.split(">");
            int[][] square = new int[splitString.length][splitString.length];

            // remove <, > and - characters and push the numbers into the square
            for (int i = 0; i < splitString.length; i++) {
                splitString[i] = splitString[i].replaceAll("[<>-]", "");
                for (int j = 0; j < splitString.length; j++) {
                    square[i][j] = Integer.parseInt(splitString[i].substring(j, j + 1));
                }
            }

I don’t feel like this is very clean but it works. Does anyone have an idea on how to improve readability?

>Solution :

I assume "<num-num-num><num-num-num><num-num-num>" would define a 3×3 grid so I would use the following approach:

  • split the string into a string per row so we get "num-num-num". That means:
    • remove the leading and trailing angular brackets
    • split at "><" and remove it
  • split each row at "-" to get the individual numbers
  • parse the numbers and assign them to the grid

Some code example:

String input = "<11-12-13><21-22-23><31-32-33>";
 
//remove leading < and trailing > then split at ><   
String[] inputRows = input.substring(1,input.length()-1).split("><");
    
int[][] grid = new int[inputRows.length][];
    
for( int r = 0; r < inputRows.length; r++) {
    //split the row at -
    String[] cells = inputRows[r].split("-");
        
    //convert the array of strings to an array of int by parsing each cell
    grid[r] = Arrays.stream(cells).mapToInt(Integer::parseInt).toArray();
}

Leave a Reply