按指定长度和编码拆分中英混合字符串,拆分中英,/** * 按指
分享于 点击 21208 次 点评:25
按指定长度和编码拆分中英混合字符串,拆分中英,/** * 按指
/** * 按指定长度和编码拆分中英混合字符串 * @param text 被拆分字符串 * @param length 指定长度,即子字符串的最大长度 * @param encoding 字符编码 * @return 拆分后的子字符串列表 * @throws UnsupportedEncodingException */ public static ArrayList split(String text, int length, String encoding) throws UnsupportedEncodingException { ArrayList texts = new ArrayList(); int pos = 0; int startInd = 0; for(int i=0;text!=null&&i<text.length();) { byte[] b = String.valueOf(text.charAt(i)).getBytes(encoding); if(b.length>length) { i++; startInd = i; continue; } pos += b.length; if(pos>=length) { int endInd; if(pos==length) { endInd = ++i; } else { endInd = i; } texts.add(text.substring(startInd, endInd)); pos = 0; startInd = i; } else { i++; } } if(startInd<text.length()) { texts.add(text.substring(startInd)); } return texts; } /** * 指定长度按UTF-8编码拆分中英混合字符串,即一个非ASCII码长度为3 * @param text 被拆分字符串 * @param length 指定长度,即子字符串的最大长度 * @return */ public static ArrayList split(String text, int len) { try { return split(text, len, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } public static void main(String[] args) { System.out.println(split("中华人21民共a和国1", 0)); System.out.println(split("中华人21民共a和国1", 1)); System.out.println(split("中华人21民共a和国1", 2)); System.out.println(split("中华人21民共a和国1", 4)); System.out.println(split("中华人21民共a和国1", 8)); System.out.println(split("中华人21民共a和国1", 16)); System.out.println(split("中华人21民共a和国1", 32)); System.out.println(split("中华人民共和国", 0)); System.out.println(split("中华人民共和国", 1)); System.out.println(split("中华人民共和国", 2)); System.out.println(split("中华人民共和国", 4)); System.out.println(split("中华人民共和国", 8)); System.out.println(split("中华人民共和国", 16)); System.out.println(split("中华人民共和国", 32)); System.out.println(split("zhrmghgzhrmghg", 0)); System.out.println(split("zhrmghgzhrmghg", 1)); System.out.println(split("zhrmghgzhrmghg", 2)); System.out.println(split("zhrmghgzhrmghg", 4)); System.out.println(split("zhrmghgzhrmghg", 8)); System.out.println(split("zhrmghgzhrmghg", 16)); System.out.println(split("zhrmghgzhrmghg", 32)); }Output:[][2, 1, a, 1][21, 1][中, 华, 人2, 1民, 共a, 和, 国1][中华, 人21民, 共a和, 国1][中华人21民, 共a和国1][中华人21民共a和国1][][][][中, 华, 人, 民, 共, 和, 国][中华, 人民, 共和, 国][中华人民共, 和国][中华人民共和国][][z, h, r, m, g, h, g, z, h, r, m, g, h, g][zh, rm, gh, gz, hr, mg, hg][zhrm, ghgz, hrmg, hg][zhrmghgz, hrmghg][zhrmghgzhrmghg][zhrmghgzhrmghg]//该片段来自于http://byrx.net
用户点评