我使用以下代码来分割 (<x-coordinate>,<y-coordinate>)
:
String startPointStr = InputPattern.parsePoint(args.get(0));
String[] startCoords = startPointStr.substring(1, startPointStr.length() - 1).split(",");
Point startPoint = new Point(Integer.parseInt(startCoords[0]), Integer.parseInt(startCoords[1]));
现在,我想修改代码,使其也适用于 (<x-coordinate>,<y-coordinate>),(<x-coordinate>,<y-coordinate>)
。
最后我需要两个点,每个点有两个值。
如何做到这一点?
最佳答案
再仔细看看,一个有效的解决方案就像发现的代码示例 here这将忽略所有不是一系列数字的值。
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("(100,200),(300,400)");
ArrayList<Integer> values = new ArrayList<>();
while(m.find())
values.add(Integer.parseInt(m.group()));
ArrayList<Point> points = new ArrayList<>();
if(values.size() % 2 == 0)
for(int i = 0; i < values.size(); i += 2)
points.add(new Point(values.get(i), values.get(i + 1)));
for(Point point : points)
System.out.println(point.x + ", " + point.y);
但是,如果您不担心效率问题,则多重拆分解决方案足以满足您的目的。
关于java - 分割字符串以获取坐标/点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60216908/