简体   繁体   中英

Java Get Map Of X-Y Coordinates From String

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' .

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:

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'

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

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