【发布时间】:2018-04-17 18:06:42
【问题描述】:
我有一个包含这样坐标的字符串:
String coord="-7.21548 1.25434,2.1648 0.154654,..."
其中第一个双精度代表 x 坐标,而第二个是 y 坐标。坐标由空格和逗号分隔。如何在 Java 中获取这些点的坐标?
【问题讨论】:
标签: java regex double coordinates extract
我有一个包含这样坐标的字符串:
String coord="-7.21548 1.25434,2.1648 0.154654,..."
其中第一个双精度代表 x 坐标,而第二个是 y 坐标。坐标由空格和逗号分隔。如何在 Java 中获取这些点的坐标?
【问题讨论】:
标签: java regex double coordinates extract
你可以试试:
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) 包含找到的完整匹配(点)。
注意-上述方法完美只有在最后一个点的坐标后跟一个逗号,否则它将匹配到但不包括最后一个点的点一个。
【讨论】:
使用循环进行迭代,直到到达逗号并将其存储在变量中。然后将变量字符串转换成双精度。
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);
}
【讨论】: