2016-04-15 151 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); 
     } 
    } 
}