简体   繁体   中英

How to divide string (x1,y1)(x2,y2) format

how to divide string (x1,y1)(x2,y2) format

for example String is (100,200) (300,600) and i am creating objects(point)

class point{
    int x;
    int y;
}

i tried using StringTokenizer but this is not the proper way.

I would do something like this -

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

Which, when I run it, outputs -

[(100, 200), (300, 600)]

You can create Point objects from the String as shown below:

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()));
        }
    }
}

Trim leading/trailing brackets and split on bracket pairs, then for each x/y set, split on comma:

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
}

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