Java Get Map Of X-Y Coordinates From String
-
24-05-2021 - |
Question
Is there any way to get a map of java.awt.Point
s from a String? Or even just a single point on that String. For example for "xyz123\nabc123"
coordinate (0, 1)
would be 'a'
.
Solution
There is nothing built-in for that.
You can try and parse that string into a 2D char array or a vector of char arrays (depending on if you know how many lines in total or not).
Given "xyz123\nabc123" as str
:
//split it by newline, should work on windows/unix
String lines[] = str.split("\\r?\\n");
char[][] map = new char[lines.length][];
//fill up map, each row is a new line
for(int i = 0; i < lines.length; i ++)
map[i] = lines[i].toCharArray();
//map[0][2] returns 'z'
OTHER TIPS
It can be done but it's not a common representation so don't expect to find it done.
A String is not that different from a char array so these might help you:
Not going to question your motive but here is one way:
String find(String[] a, int x, int y) {
try {
return String(a[x].charAt(y)); // or y+1 in your example
}
catch (Exception exc) {
return NULL;
}
}
...
String s = "xyz123\nabc546";
String[] sa = s.split("\\n");
find(sa, 0, 0); // returns "x"
find(sa, 1, 2); // returns "c"
find(sa, 3, 2); // returns NULL
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow