【问题标题】:Extracting double coordinates form string java从字符串java中提取双坐标
【发布时间】:2018-04-17 18:06:42
【问题描述】:

我有一个包含这样坐标的字符串:

String coord="-7.21548 1.25434,2.1648 0.154654,..."

其中第一个双精度代表 x 坐标,而第二个是 y 坐标。坐标由空格和逗号分隔。如何在 Java 中获取这些点的坐标?

【问题讨论】:

  • 这里被问过很多次,在这个社区有答案。你最好search你的问题,或者至少在你输入问题时回顾类似的问题下拉。您最好咨询this page 以了解如何提出更好的问题,这些问题将很快得到解答。对于这种特殊情况,请查看@jhamon 提到的页面

标签: java regex double coordinates extract


【解决方案1】:

你可以试试:

String[] points = coord.split("\\s*[,]\\s*");

split() 方法返回一个字符串数组。

解释-

\\s*   ->  Indicates zero-or-more spaces
[,]    ->  Indicates a comma (which is basically that one present between the points)
\\s*   ->  Indicates that there may be zero-or-more spaces between the comma and the next point

但是,如果您的文本可能包含一些单词,那么您最好通过导入 java.util.regex 包来使用 Pattern 和 Matcher 类:

String coords = "Hi there! 2.3 12.6786, -1234 7.3, 34 35, are the points!";

Pattern p = Pattern.compile("[0-9\\-][0-9 .\\-]+(?=,)");
Matcher m = p.matcher(coords);

while(m.find())
    System.out.println("Point found = '" + m.group(0) + "'");

输出如下:

Point found = '2.3 12.6786'
Point found = '-1234 7.3'
Point found = '34 35'

m.group(0) 包含找到的完整匹配(点)。

注意-上述方法完美只有在最后一个点的坐标后跟一个逗号,否则它将匹配到但不包括最后一个点的点一个。

【讨论】:

  • 感谢@Coffeehouse 的回答,效果很好
  • @OussamaDJIDJ 如果您觉得某个答案已经令人满意地解决了您的问题,请考虑将其标记为有帮助,甚至点赞!这肯定会有助于任何未来的参考:)
【解决方案2】:

使用循环进行迭代,直到到达逗号并将其存储在变量中。然后将变量字符串转换成双精度。

String xcoord,ycoord;
Double x,y;

while(coord[i++]!= 0)
{
    while(coord[i]!= ',')
        xcoord = coord[i];

    x = Double.parseDouble(xcoord);

    while(coord[i]!= ',')
        ycoord = coord[i];

    y = Double.parseDouble(ycoord);

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 2011-06-14
    相关资源
    最近更新 更多