你可以用一个单一的分裂做到这一点(当然,这可能不是最有效的运行,但这是简洁,较小的代码编写):
String[] arr = str.split("(?<=\\G..)");
,然后用Arrays#asList()
方法得到List<String>
。
正则表达式模式在前面有2个字符的空白处分开 - ..
,但忽略之前匹配中已考虑的字符 - \\G
。主播\\G
匹配前一场比赛结束的位置。
String str = "00122334455667788990875645346787659870984780";
String[] arr = str.split("(?<=\\G..)");
System.out.println(Arrays.asList(arr));
打印:
[00, 12, 23, 34, 45, 56, 67, 78, 89, 90, 87, 56, 45, 34, 67, 87, 65, 98, 70, 98, 47, 80]
这里是如何拆分您的字符串进行:
" 00 1 2 2334455667788990875645346787659870984780" (whitespaces represent empty string)
// | | |
// split, no-split, split -> gives 12
// | | | |
// \ /\ /
// gives 00 as the preceding two characters are `1` and `0`.
// but 0 is already considered for the previous empty string
参考:
如果运行时性能是一个问题,那么你就可以用简单的循环去:
String str = "00122334455667788990875645346787659870984780";
List<String> list = new ArrayList<String>();
for (int i = 0; i < str.length(); i += 2) {
list.add(str.substring(i, i + 2));
}
System.out.println(list);
但是你可以自己查一下,正则表达式拆分是否是真的大型字符串的性能瓶颈,并且适当地对它们进行基准测试。
我测试了两种方法 - 分割和循环。正如所期望的,循环比分割字符串长度几乎高4-5倍,例如1000
。在几个连续运行
public static void usingSplit(String str) {
String[] arr = str.split("(?<=\\G..)");
List<String> list = Arrays.asList(arr);
}
public static void usingLoop(String str) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < str.length(); i += 2) {
list.add(str.substring(i, i + 2));
}
}
// Warm up JVM
for (int i = 0; i < 1000000; ++i) {
usingSplit(str);
}
for (int j = 0; j < 1000000; j++) {
usingLoop(str);
}
long nano = System.nanoTime();
for (int i = 0; i < 1000000; ++i) {
usingSplit(str);
}
System.out.println("Time with usingSplit(): " + (System.nanoTime() - nano) * 1.0/Math.pow(10, 9) + " Seconds");
nano = System.nanoTime();
for (int j = 0; j < 1000000; j++) {
usingLoop(str);
}
System.out.println("Time with usingLoop(): " + (System.nanoTime() - nano) * 1.0/Math.pow(10, 9) + " Seconds");
输出:
Run 1:
Time with usingSplit(): 34.391315143 Seconds
Time with usingLoop(): 7.515221612 Seconds
Run 2:
Time with usingSplit(): 33.41518869 Seconds
Time with usingLoop(): 7.868896218 Seconds
如果有人认为该基准测试结果是有缺陷的,那么请记下它的意见。
什么是您的效率标准?性能?简明? – assylias
它应该能够尽快处理这样的大字符串。 :-) – dreamer