1. 程式人生 > >JAVA擷取字元,防止半個漢字

JAVA擷取字元,防止半個漢字


/**
* 字串含中文截位,每個中文漢字按兩個位元組計算,其他可見字元按一個位元組計算
* 在遇到截位時候碰到半個漢字的時候,捨棄半個漢字對應的位元組防止插入資料庫亂碼
* @param str 源字串
* @param maxByteLen 截位後的字串最大長度
* @return
*/
public static String subString(String str, final int maxByteLen) {
int len=maxByteLen;
if (str == null || maxByteLen <= 0) {
return "";
}
byte[] bStr;
try {
bStr = str.getBytes("GBK"); //位元組流
if (maxByteLen >= bStr.length) {
return str;
}
String cStr = new String(bStr, maxByteLen - 1, 2,"GBK");
if (cStr.length() == 1 && str.contains(cStr)) {
len--;
}
return new String(bStr, 0, len,"GBK"); //重新組字串
} catch (UnsupportedEncodingException e) {
throw new java.lang.RuntimeException("substring fail ");
}
}