EngineUtil { public static String[] split(final String str, final char delim, final int maxTokens) { int max = maxTokens; List<String> result = new ArrayList<String>(max); if (max == 0) { max = -1; } int curr = -1; int prev = 0; while (true) { ++curr; if (curr == str.length()) { result.add(str.substring(prev, str.length())); --max; break; } if (str.charAt(curr) == delim) { result.add(str.substring(prev, curr)); --max; prev = curr + 1; } if (max == 0) { break; } } return result.toArray(new String[result.size()]); } private  EngineUtil(); static boolean hasText(String text); static String[] split(final String str, final char delim, final int maxTokens); static String[] split(final String str, final char delim); static String[] split2(final String str, final char delim); static String trimAllWhitespace(final String str);  }
@Test public void testSplit() { Map<String, String[]> casesMap = new LinkedHashMap<String, String[]>(); casesMap.put("A,B,C", new String[]{"A", "B", "C"}); casesMap.put(",A,B", new String[]{"", "A", "B"}); casesMap.put(",A,B,", new String[]{"", "A", "B", ""}); casesMap.put(",,", new String[]{"", "", ""}); casesMap.put(" ,, ", new String[]{" ", "", " "}); casesMap.put("A,,B,,C,", new String[]{"A", "", "B", "", "C", ""}); casesMap.put("AA,BB", new String[]{"AA", "BB"}); casesMap.put(",AA,BB", new String[]{"", "AA", "BB"}); casesMap.put(",AA,BB,", new String[]{"", "AA", "BB", ""}); casesMap.put("AA,,BB", new String[]{"AA", "", "BB"}); for (Map.Entry<String, String[]> e : casesMap.entrySet()) { String str = e.getKey(); String[] expected = e.getValue(); String[] result = EngineUtil.split(str, ','); assertArrayEquals(expected, result); } }
@Test public void testSplit__max() { Map<String, String[]> casesMap = new LinkedHashMap<String, String[]>(); casesMap.put("A,B,C", new String[]{"A", "B"}); casesMap.put(",A,B", new String[]{"", "A"}); casesMap.put(",A,B,", new String[]{"", "A"}); casesMap.put(",,", new String[]{"", ""}); casesMap.put("A,B", new String[]{"A", "B"}); casesMap.put("A,", new String[]{"A", ""}); casesMap.put(",", new String[]{"", ""}); for (Map.Entry<String, String[]> e : casesMap.entrySet()) { String str = e.getKey(); String[] expected = e.getValue(); String[] result = EngineUtil.split(str, ',', 2); assertArrayEquals(expected, result); } }