如何解析由坐标列表组成的字符串?

时间:2014-07-22 09:48:32

标签: java eclipse xml-parsing

如何解析由表单坐标列表组成的字符串:

-123.141026905408,49.2636144033057,0 -123.141047822927,49.2631 

进入单独的经度 - 纬度对?

3 个答案:

答案 0 :(得分:0)

首先使用str.splot(",")进行拆分,然后按以下方式进行配对

String s[] = str.split(",");
for(int i = 0; i< s.length; i+=2){
   double lat = Double.parseDouble(s[i+1]);
   double longi = Double.parseDouvle(s[i]);
   //use pair
}

答案 1 :(得分:0)

这是代码 -

String latlong="-123.141026905408,49.2636144033057,0 -123.141047822927,49.2631";
String[] pairs = latlong.split(",");
for (int i = 0; i < pairs.length; i++) {
    System.out.print("Lat = "+pairs[i]);
    System.out.println(", Long = "+pairs[i+1]);
    i++;
}

输出 -

Lat = -123.141026905408, Long = 49.2636144033057
Lat = 0 -123.141047822927, Long = 49.2631

答案 2 :(得分:0)

您可以使用Scanner类并执行以下操作:

String latlong="-123.141026905408,49.2636144033057,0 -123.141047822927,49.2631";

Scanner in = new Scanner(latlong);

double[] coord1 = getCoordArray(new Scanner(in.next()));
double[] coord2 = getCoordArray(new Scanner(in.next()));

double[] getCoordArray(Scanner coordinateScanner){
    double[] result= new double[2];

    coordinateScanner.useDelimiter(",");

    result[0] = coordinateScanner.nextDouble();
    result[1] = coordinateScanner.nextDouble();

    return result;
}

这里我将每个坐标作为数组返回。无论如何你都可以这样做,我猜,它很直接。我个人会创建一个Coordinate类,其构造函数如下:

public Coordinate(double x, double y){
    this.x = x;
    this.y = y;
}

并使getCoordArray()方法返回:

new Coordinate(coordinateScanner.nextDouble(), coordinateScanner.nextDouble())