處理中英混排字串時,常需按「雙位元組長度」(中文算 2、英文算 1)截取並加省略號。本工具方法精確實現此邏輯,支援含中文、全形符號等雙位元組字元的字串截取。
getBytes().length 獲取字串實際位元組長度[^\x00-\xff] 判斷雙位元組字元(含中文、日文、韓文、全形符號等)...,未超長返回原字串
/**
* 按雙位元組長度截取字串
* @param str 原始字串
* @param len 目標雙位元組長度(中文算2,英文算1)
* @return 截取後字串,超長加 "..."
*/
public static String getStrByLength(String str, int len) {
if (str == null) return "";
int byteLen = str.getBytes().length;
if (byteLen > len * 2) {
StringBuffer sb = new StringBuffer();
char[] arr = str.toCharArray();
for (int i = 0, j = 0; i < arr.length && j < len * 2; i++) {
// 判斷是否雙位元組字元
if (String.valueOf(arr[i]).matches("[^\\x00-\\xff]")) {
j += 2;
} else {
j++;
}
// 邊界處理:若剛好達到長度-1且下一字元是雙位元組,則停止
if (j == len * 2 - 1 && String.valueOf(arr[i]).matches("[^\\x00-\\xff]")) {
continue; // 不追加該字元
} else {
sb.append(arr[i]);
}
}
return sb.toString() + "...";
}
return str;
}
getStrByLength("Hello世界", 5); // "Hello..." (H e l l o = 5, 世 界 = 4 超長)
getStrByLength("Hello世界", 7); // "Hello世..." (5+2=7 剛好)
getStrByLength("Hello", 10); // "Hello" (未超長)
getBytes() 使用平台預設編碼,跨平台建議指定 getBytes("UTF-8") 或 GBK[^\x00-\xff] 涵蓋所有非 ASCII 字元,比單純判斷中文範圍 [\u4e00-\u9fa5] 更通用