Its Andrew
Its Andrew

Reputation: 155

String of coordinates to array

I'm attempting to take in a string of coordinates and convert them to an integer array of arrays as seen below:

myLine (string):

1-2 9-5 4-5 3-6 5-9

desired output:

[[1,2],[9,5],[4,5],[3,6],[5,9]]

So far I have split the string by spaces to isolate each coordinate:

result = new int[5][2];    
String[] temp_split = myLine.split(" ");

This has given me each coordinate in individual arrays, however I'm unsure as to how to extract each integer element and place it in an array

Where I am currently at:

for (int i = 0; i < result.length; i++) {
    for (int j = 0; j < result[1].length; j++) {
        result[i][j] = Integer.parseInt(temp_split[i][j]);
            }
        }

That does not even give me close to my desired result.

Upvotes: 1

Views: 540

Answers (3)

WJS
WJS

Reputation: 40034

This is a perfect situation to use streams.

  • split on one or more spaces
  • split each of those pairs on - and convert to a int
  • return an array of each pair
  • and return all the pairs as an array of arrays.
String s = "1-2 9-5 4-5 3-6 5-9";

int[][] pairs = Arrays.stream(s.split("\\s+"))
        .map(pair -> Arrays.stream(pair.split("-"))
                .mapToInt(Integer::parseInt).toArray())
        .toArray(int[][]::new);

System.out.println(Arrays.deepToString(pairs));

Prints

[[1, 2], [9, 5], [4, 5], [3, 6], [5, 9]]

Upvotes: 1

Henry Twist
Henry Twist

Reputation: 5980

You're on the right track. However you seem to be trying to do too much all at once. I would recommend taking it step by step. So first we need to split the String into the pairs of co-ordinates:

String[] split1 = input.split(" ");

Then we can loop through that array and split each item:

String[] split2 = split1[i].split("-");

Finally you can obtain your result:

result[i][0] = Integer.parseInt(split2[0]);
result[i][1] = Integer.parseInt(split2[1]);

So the final solution would look like this:

String[] split1 = input.split(" ");

for (int i = 0; i < split1.length; i++) {

    String[] split2 = split1[i].split("-");

    result[i][0] = Integer.parseInt(split2[0]);
    result[i][1] = Integer.parseInt(split2[1]);
}

Alternatively if you wanted something shorter, you could split by both the space and - characters and do something like this:

String[] split = input.split("[ |-]");
for (int i = 0; i < split.length; i+=2) {

    result[i / 2][0] = Integer.parseInt(split[i]);
    result[i / 2][1] = Integer.parseInt(split[i + 1]);
}

however this is probably overly complex for this use case.

Upvotes: 2

idan ovadia
idan ovadia

Reputation: 239

somting like that

String[] temp_split = myLine.split(" ");
int [][] result = new int[temp_split.length][2];
for (int i = 0; i < result.length; i++) {
  String[] temp_split2 = myLine.split("-");
  result[i][0] = Integer.parseInt(temp_split2[0])
  result[i][1] = Integer.parseInt(temp_split2[1])
}  

Upvotes: 0

Related Questions