如何划分字符串(x1,y1)(x2,y2)格式
例如String是(100,200) (300,600)
,我正在创建对象(点)
class point{
int x;
int y;
}
我尝试使用StringTokenizer
,但这不是正确的方法。
答案 0 :(得分:1)
我会做这样的事情 -
public static class Point {
public Point(int x, int y) {
this.x = x;
this.y = y;
}
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public String toString() {
return "(" + String.valueOf(x) + ", "
+ String.valueOf(y) + ")";
}
public static Point[] fromString(String in) {
if (in == null) {
return null;
}
List<Point> al = new ArrayList<Point>();
int p = 0;
for (;;) {
int openPos = in.indexOf('(', p);
if (openPos > -1) {
int closePos = in.indexOf(')', openPos + 1);
if (closePos > -1) {
String str = in.substring(openPos + 1,
closePos);
String[] t = str.split(",");
p = closePos + 1;
if (t.length != 2) {
continue;
}
al.add(new Point(Integer.valueOf(t[0]
.trim()), Integer.valueOf(t[1].trim())));
} else {
break;
}
} else {
break;
}
}
return al.toArray(new Point[al.size()]);
}
}
public static void main(String[] args) {
Point[] pts = Point
.fromString("(100,200) (300,600)");
System.out.println(Arrays.toString(pts));
}
当我运行它时,输出 -
[(100, 200), (300, 600)]
答案 1 :(得分:1)
您可以从String创建Point对象,如下所示:
public class Sample {
static List<Point> points = new ArrayList<Point>();
public static void main(String[] args) {
String s = "(100,200) (300,600)";
toPoints(s.replaceAll("[(),]", " "));
for (Point i : points)
System.out.println("points = " + i);
}
private static void toPoints(final String value) {
final Scanner scanner;
scanner = new Scanner(value);
while (scanner.hasNextInt()) {
points.add(new Point(scanner.nextInt(), scanner.nextInt()));
}
}
}
答案 2 :(得分:0)
修剪前导/尾随括号并在括号对上拆分,然后对于每个x / y集,用逗号分隔:
for (String pair : str.replaceAll("^\\(|\\)$", "").split("\\)\\s*\\(")) {
int x = Integer.parseInt(pair.split(",")[0]);
int y = Integer.parseInt(pair.split(",")[1]);
Point point = new Point(x, y);
// do something with point
}