-2

I have a series of strings, each of the format :

"{3.242, 87611}, {5.658, 7.3731}, {5.547, 8.7631} ......"

Each pair of numbers in curly brackets represents one Latitude/Longitude point (and each number is of type double).

I want to parse the string so that each point in the string is represented as a separate Lat/Lon object, that I store in a list of points.

I am pretty new to Java (and parsing). I have been looking at a lot of examples but I'm still really confused as to how to even begin. How do I go about doing this?

Ramya Rao
  • 86
  • 7

2 Answers2

1

You can use regExp to fetch points first,

String str = "{3.242, 87611},{5.658, 7.3731}";
Pattern pattern = Pattern.compile("\\{(.*?)\\}");
Matcher match = pattern.matcher(str);

while(match.find()) {
   System.out.println(match.group(1));
}

OUTPUT

3.242, 87611
5.658, 7.3731

Now you can just use split to find two points and you can parse them to Double. Note here (.*?) is a group which means any String

Community
  • 1
  • 1
akash
  • 22,664
  • 11
  • 59
  • 87
0

Assuming you have already have this String in some variable str, you can split str into it's component numbers

String[] splitNumbers = str.split("[{}, ]+");

then iterate over this list and use each pair of numbers to construct a Coordinate object.

Coordinate[] coords = new Coordinate[splitNumbers.length/2];
for(int i=0; i < splitNumbers.length-2;i+=2){
    double longitude = Double.paresDouble(splitNumbers[i]);
    double latitude = Double.paresDoublesplitNUmbers[i+1]);
    coords[i/2] = new Coordinate(longitude,latitude);
 }
ankh-morpork
  • 1,732
  • 1
  • 19
  • 28