我試圖在每次出現第N次時分割一個字符串,但缺少最後一個值。這是預期的結果。如何在Java中字符的第N次出現時分割字符串
輸入:String str = "234-236-456-567-678-675-453-564";
輸出:
234-236-456
567-678-675
453-564
N=3
這裏,其中str
應在每-
第三occurence進行分割。
我試圖在每次出現第N次時分割一個字符串,但缺少最後一個值。這是預期的結果。如何在Java中字符的第N次出現時分割字符串
輸入:String str = "234-236-456-567-678-675-453-564";
輸出:
234-236-456
567-678-675
453-564
N=3
這裏,其中str
應在每-
第三occurence進行分割。
也許最糟糕的途徑之一,而無需使用功能在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;
}
}
}
試試這個。
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]
也許你可以在lookbehind中解釋'\\ G'。 –
您可以嘗試使用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
這工作就像一個魅力。謝謝弗蘭克! – AyrusTerminal
歡迎你 – Frank
替換'for(; i
Lino