按指定個數批量拆分字符串app
好比「1,2,3,4,5,6,7,8,9,0」ui
每3個進行拆分spa
splitString("1,2,3,4,5,6,7,8,9,0",",",3)
返回:
1,2,3,
4,5,6,
7,8,9,
0,
private List<String> splitString(String data, String ch, int n) { if (!data.endsWith(ch)) { data = data + ch; } List result = new ArrayList(); int i = 0; StringBuilder sb = new StringBuilder(); while (data.indexOf(ch) > 0) { int pos = data.indexOf(ch); if (i < n) { sb.append(data.substring(0, pos + 1)); data = data.substring(pos + 1); i += 1; } if (i == n) { result.add(sb.toString()); sb = new StringBuilder(); i = 0; } } if (sb.length() > 0) { result.add(sb.toString()); } return result; }