一种特定的场景,需要检测指定字符串的长度,但是一个中文字需要占用2个长度,另外还需要截图字符串长度,指定的长度也是按1个中文字符2个长度来算
代码如下,说明写在注释里:
/** * 判断是否为汉字 */ private static boolean isChineseChar(char c) { Character.UnicodeBlock ub = Character.UnicodeBlock.of(c); return 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; } /** * 获取汉字的长度,长度按汉字为2,其他为1 */ public static int getChineseStringLength(String str) { int len = 0; for (int i = 0; i < str.length(); i++) { if (isChineseChar(str.charAt(i))) { // 如果是汉字,长度加2 len += 2; } else { // 如果是其他字符,长度加1 len += 1; } } return len; } /** * 填充或截断字符串,长度按汉字为2,其他为1 * 如果不足的部分,用空格填充 */ public static String paddingOrTruncateChinese(String str, int length) { if (str == null) { str = ""; } int len = 0; StringBuilder result = new StringBuilder(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (isChineseChar(c)) { len += 2; } else { len++; } if (len <= length) { result.append(c); } else { break; } } // Padding if the length is less than the specified length while (len < length) { result.append(" "); len++; } return result.toString(); }
文章评论