简体   繁体   中英

Splitting a string with two (x,y) integers in it - Java

My question is simply - I have a string that is "2 1". 2 is to represent the int x coordinate and 1 is to represent the y coordinate.

I wan't my result to be something like this:

int x;

int y;

Sting example = "2 1";

//some sort of split happens

result..

x = 2 //these are both integers

y = 1

I was thinking of doing a substring for the 2 and the 1...then converting it to an int. -- maybe there is another way? a better way?

Thanks!

You could combine a String.split(String) with Integer.parseInt(String) like

String example = "2 1";
String[] arr = example.split("\\s+"); // <-- one (or more) whitespace
int x = Integer.parseInt(arr[0]);
int y = Integer.parseInt(arr[1]);

I suggest you to use some kind of delimiter(say ~) to seperate your x coordinate and y coordinate. Then you can simply do like this.

int x = Integer.parseInt(example.split("~")[0]);
int y = Integer.parseInt(example.split("~")[1]);

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