2013-12-08 159 views
0

我有分割字符串,每次

String input = "one two three four five six seven"; 

是否有與String.split()工程搶(高達)在同一時間兩個詞,使得正則表達式兩個字:

String[] pairs = input.split("some regex"); 
System.out.println(Arrays.toString(pairs)); 

結果在此:

[one two,two three, three four,four five,five six,six seven] 

回答

5
String[] elements = input.split(" "); 
List<String> pairs = new ArrayList<>(); 
for (int i = 0; i < elements.length - 1; i++) { 
    pairs.add(elements[i] + " " + elements[i + 1]); 
} 
2

號隨着String.split() ,你得到的東西不能重疊。

例如你可以得到:"one two three four" - >{"one","two","three","four"},但不是{"one two","two three", "three four"}

+0

但JB Nizet的答案肯定會解決你的問題 – jgon