Java截取指定byte位数的UTF-8字符串
在实际编程中可能会遇到,如将字符串"aa中bb国cc"截取成最长8个字节的字符串,但因为utf-8是可变长编码方式,也就是说字符串"a"和字符串"中",在utf-8中所占的位数是不一样的。因此如果简单的取8个字节的话,很可能造成非ASCII的编码被错误截断,引起乱码。
下面代码能解决上述问题(仅对utf-8的编码格式有效)
/** * 按指定长度截断字符串 * @param s * @param size * @return */ public static String substring(String s, int size) { if (size <= 0) { return ""; } else if (s == null || s.getBytes().length <= size) { return s; } int index = 0; byte[] bs = s.getBytes(); if ((bs[size] >> 7) == 0x0 || ((bs[size] >> 6) & 0x03) == 0x03) { index = size; } else { for (int i = size - 1; i >= 0; i--) { if (((bs[i] >> 6) & 0x03) == 0x03) { index = i; break; } } } return new String(Arrays.copyOf(s.getBytes(), index)); }