拆分包含两个 (x,y) 整数的字符串 - Java

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

我的问题很简单——我有一个字符串“2 1”。 2代表int x坐标,1代表y坐标。

我不希望我的结果是这样的:

int x;

int y;

Sting example = "2 1";

//发生某种分裂

结果..

x = 2 //these are both integers

y = 1

我正在考虑为 2 和 1 做一个子字符串...然后将其转换为 int。 ——也许还有别的办法?有更好的方法吗?

谢谢!

您可以将 String.split(String) with Integer.parseInt(String) 组合成

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]);

我建议您使用某种定界符(比如 ~)来分隔您的 x 坐标和 y 坐标。那么你可以简单地这样做。

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