2016-04-15 148 views
1

我有一个由x和y坐标列表组成的字符串。 x和y坐标用逗号分隔,并且每个坐标以指示坐标结束的点结束。我需要向下突破这个字符串来获得每个x和y坐标,但我不能让我的for循环正常基于字符拆分字符串

工作例如:

String coords= "3,1.2,0.1,1.0,2.1,3.2,3.3,3."; 

每个逗号分隔的X和Y坐标。点(。)结束坐标并开始一个新的坐标。所以实际的坐标列表就像这样。

  • X:3,Y:1
  • X:2,Y:0
  • X:1,Y:1
  • X:0,Y:2
  • .. .. ....
  • .... ....

的原因,它是在这样一个奇怪的方式完成是因为我正在研究一个机器人项目,并且存在内存问题,所以我不能使用数组作为坐标,因此必须将单个字符串从PC传递到嵌入式系统,需要将其分解为坐标。

+0

你能看到我的单行方案。 –

回答

1

试试这个。

String coords= "3,1.2,0.1,1.0,2.1,3.2,3.3,3."; 
    for (int i = 0, j = 0; i < coords.length(); i = j + 1) { 
     j = coords.indexOf(".", i); 
     if (j == -1) break; 
     int k = coords.indexOf(",", i); 
     int x = Integer.parseInt(coords.substring(i, k)); 
     int y = Integer.parseInt(coords.substring(k + 1, j)); 
     System.out.printf("X:%d, Y:%d%n", x, y); 
    } 
+0

谢谢。工作得很好。 – PRCube

1
String coords= "3,1.2,0.1,1.0,2.1,3.2,3.3,3."; 
for(int i=0; i< coords.length(); i++) 
{ 
    if (coords.charAt(i) == '.') 
    { 
     String s = coords.substring(i); 

     System.out.println("X:"+ s.split(",")[0] + " " + "Y:"+s.split(",")[1]); 
    } 

} 
+0

不幸的是,这是行不通的。我不能使用数组,这是为了一个机器人项目,并且存在内存约束。出于某种原因我甚至没有得到任何输出。 – PRCube

+0

您确切的要求是什么?把所有的X,Y都放在一个字符串中? – SomeDude

+0

是的,坐标是作为单个字符串传递的。我需要处理并打破每个字符串(读取每个字符)并使用它。即使我可以得到它的输出,我也可以从那里管理它。 – PRCube

0

如果你的目标是再一个办法是只使用字符串replace()方法,

NOfor循环,NOsplit()NOarray这样得到输出字符串:

String s = "3,12.23,0.1,1.0,2.1,3.2,3.3,3"; 
s = "X:"+s.replace(",", ",Y:").replace(".", "\nX:");   
System.out.println(s) 

输出:

X:3,Y:1 
X:2,Y:0 
X:1,Y:1 
X:0,Y:2 
X:1,Y:3 
X:2,Y:3 
X:3,Y:3 
0

一个相当简单的方法是使用正则表达式。

Pattern pattern = Pattern.compile("(\\d+),(\\d+)\\."); 

Matcher matcher = pattern.matcher(inputString); 
while (matcher.find()) { 
    int x = Integer.parse(matcher.group(1)); 
    int y = Integer.parse(matcher.group(2)); 
    // do whatever you need to do to x and y 
} 
0

使用分割法(第一次点之间,第二次分裂逗号之间的分裂)

public class SplitCoordinates { 
    static public void main(String[] args) { 
     String s = "3,1.2,0.1,1.0,2.1,3.2,3.3,3"; 
     for (String s2: s.split("\\.")) { 
      String[] s3 = s2.split("\\,"); 
      int x = Integer.parseInt(s3[0]); 
      int y = Integer.parseInt(s3[1]); 
      System.out.println("X:" + x + ",Y:" + y); 
     } 
    } 
}