按字节数截取含中文的字符串
帖子地址:http://www.iteye.com/topic/1037773
判断一个字符是否为中文参考文章地址:http://blog.csdn.net/Kilper/archive/2010/08/21/5829300.aspx
我的代码实现
public class Substring {public static void main(String[] args) {String str = "我ABC汉DEF";System.out.println(substring(str, 6));}/** * @param str * 字符串 * @param bytes * 需要截取的字节数 * @return 结果 */public static String substring(String str, int bytes) {if (null == str) {return null;}StringBuffer sb = new StringBuffer();// 截取了的字节数int len = 0;for (char c : str.toCharArray()) {if (isChinese(c)) {// 如果是中文,字节数加2len += 2;} else {// 如果不是中文,字节数加1len++;}if (len > bytes) {// 如果字节数大于了需要截取的,则终止break;} else {sb.append(c);}}return sb.toString();}/** * 判断一个字符是不是中文 */public static boolean isChinese(char c) {Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {return true;}return false;}}
我ABC