2017-07-26 286 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 
相关问题