2017-07-26 202 views

回答

0

也許最糟糕的途徑之一,而無需使用功能在java中可用,但像前一樣好ercise:

public static void main(String[] args){ 
     String s = "234-236-456-567-678-675-453-564"; 
     int nth =0; 
     int cont =0; 
     int i=0; 
     for(;i<s.length();i++){ 
      if(s.charAt(i)=='-') 
       nth++; 
      if(nth == 3 || i==s.length()-1){ 
       if(i==s.length()-1) //with this if you preveent to cut the last number 
       System.out.println(s.substring(cont,i+1)); 
       else 
        System.out.println(s.substring(cont,i)); 
       nth=0; 
       cont =i+1; 


      } 
     } 
    } 
+0

這工作就像一個魅力。謝謝弗蘭克! – AyrusTerminal

+0

歡迎你 – Frank

+0

替換'for(; i Lino

2

試試這個。

String str = "234-236-456-567-678-675-453-564"; 
String[] f = str.split("(?<=\\G.*-.*-.*)-"); 
System.out.println(Arrays.toString(f)); 

結果:

[234-236-456, 567-678-675, 453-564] 
+0

也許你可以在lookbehind中解釋'\\ G'。 –

0

您可以嘗試使用Java 8如下:

String str = "234-236-456-567-678-675-453-564"; 
Lists.partition(Lists.newArrayList(str.split("-")), 3) 
    .stream().map(strings -> strings.stream().collect(Collectors.joining("-"))) 
    .forEach(System.out::println); 

輸出:

234-236-456 
567-678-675 
453-564 
相關問題