StringUtils的split()方法只能以單個字符進行切分,即使在使用StringUtils.split(String str, String splitChars),splitChars傳入多個字符的字符串,也只會以splitChars中的所有包含的單個字符進行切分,具體如下:
import org.apache.commons.lang.StringUtils; public class Test { public static void main(String[] args) { String s = "0012001230010023001230023"; long time1 = System.currentTimeMillis(); String[] split1 = s.split("123"); long time2 = System.currentTimeMillis(); String[] split2 = StringUtils.split(s, "123"); long time3 = System.currentTimeMillis(); System.out.println("用時1>>>."+(time2-time1)); System.out.println("用時2>>>."+(time3-time2)); for(int i=0,len=split1.length; i<len; i++){ System.out.print(split1[i]); System.out.print("-"); } System.out.println(""); for(int i=0,len=split2.length; i<len; i++){ System.out.print(split2[i]); System.out.print("-"); } } }
運行結果:
用時1>>>.2
用時2>>>.17
001200-001002300-0023-
00-00-00-00-00-00-
另: StringUtils.split()是空指針安全的.
附StringUtils.split(String str, String separatorChars, int max)的實現源碼:
private static String[] splitWorker(String str, String separatorChars, int max, boolean preserveAllTokens) { // Performance tuned for 2.0 (JDK1.4) // Direct code is quicker than StringTokenizer. // Also, StringTokenizer uses isSpace() not isWhitespace() if (str == null) { return null; } int len = str.length(); if (len == 0) { return ArrayUtils.EMPTY_STRING_ARRAY; } List list = new ArrayList(); int sizePlus1 = 1; int i = 0, start = 0; boolean match = false; boolean lastMatch = false; if (separatorChars == null) { // 使用StringUtils.split(String str)時默認進入這個判斷,使用空字符進行切割 while (i < len) { if (Character.isWhitespace(str.charAt(i))) { if (match || preserveAllTokens) {//遇到空字符進入此判斷 ① lastMatch = true; if (sizePlus1++ == max) { i = len; lastMatch = false; } list.add(str.substring(start, i));//將截取的字符串放入list match = false; } start = ++i;//將下一個字符作為截取開始點 continue; } lastMatch = false; match = true;//如果不是separatorChars則置為true,以便下一個字符進入判斷 ① i++; } } else if (separatorChars.length() == 1) { // 截取字符是單個字符的情況 與默認空字符判斷情況相同 char sep = separatorChars.charAt(0); while (i < len) { if (str.charAt(i) == sep) { if (match || preserveAllTokens) { lastMatch = true; if (sizePlus1++ == max) { i = len; lastMatch = false; } list.add(str.substring(start, i)); match = false; } start = ++i; continue; } lastMatch = false; match = true; i++; } } else { // standard case while (i < len) { if (separatorChars.indexOf(str.charAt(i)) >= 0) {//如果被切割字符串的第i個字符在separatorChars中,則切掉 (正是此處與jdk的split不同) if (match || preserveAllTokens) { lastMatch = true; if (sizePlus1++ == max) { i = len; lastMatch = false; } list.add(str.substring(start, i)); match = false; } start = ++i; continue; } lastMatch = false; match = true; i++; } } if (match || (preserveAllTokens && lastMatch)) { list.add(str.substring(start, i)); } return (String[]) list.toArray(new String[list.size()]); }