user13244866
user13244866

Reputation:

How to parse this string of latitude/longitude coordinates in java?

I have a string, pointString.

and I'm trying to get the number values from them and add them to new LatLng variables.

Heres my code

private ArrayList<LatLng> ConvertPoints (String pointsStringInput){
        ArrayList <LatLng> points = new ArrayList<LatLng>();
        String pointsString = pointsStringInput.substring(1, pointsStringInput.length()-1);
        for (int i = 0; i < pointsString.split("lat/lng: ").length; i++){
            Log.w("INDEX", String.valueOf(i));
            if (!pointsString.split("lat/lng: ")[i].matches("none12323232321412515152124214412")){
                points.add(new LatLng (Double.parseDouble(pointsString.split("lat/lng: ")[i].split(",")[0].replace("\\(", "")), Double.parseDouble(pointsString.split("lat/lng: ")[i].split(",")[1].replace("\\)", ""))));
            }
        }
        return points;

    }

it always crashes on I=0, with java.lang.NumberFormatException: empty String

Upvotes: 0

Views: 1287

Answers (1)

azro
azro

Reputation: 54148

You did use pointsString.split("lat/lng: ") 4 times, but never print it out, but it values the following. As you split you got the parts that are before and after the delimiter, so you have the empty content before the first one.

[, (43.8457509,-79.45568817), , (43.8457509,-79.45568817), , (43.84598041,-79.45584389), , (43.845954,-79.45585094]

The easier whould be to use regular expression, as you know perfectly how the data should be lat/lng: \((-?\d+\.\d+),(-?\d+\.\d+)\)

  • \( and \) to match the real parenthesis
  • -? to match eventually a minus
  • \d+\.\d+ to match the values

  • lat/lng: \(-?\d+\.\d+,-?\d+\.\d+\) final regex, then just add () for capturing the values

private ArrayList<LatLng> ConvertPoints(String pointsStringInput) {
    ArrayList<LatLng> points = new ArrayList<>();
    Matcher m = Pattern.compile("lat/lng: \\((-?\\d+\\.\\d+),(-?\\d+\\.\\d+)\\)").matcher(pointsStringInput);
    while (m.find()) {
        points.add(new LatLng(Double.parseDouble(m.group(1)), Double.parseDouble(m.group(2))));
    }
    return points;
}

The version with Stream<MatchResult> is

private List<LatLng> ConvertPoints(String pointsStringInput) {
    return Pattern.compile("lat/lng: \\((-?\\d+\\.\\d+),(-?\\d+\\.\\d+)\\)")
            .matcher(pointsStringInput).results()
            .map(m -> new LatLng(Double.parseDouble(m.group(1)), Double.parseDouble(m.group(2))))
            .collect(Collectors.toList());
}

Upvotes: 2

Related Questions