- //str : 字符串 ; subSlength : 字节数 ;
- public static String subStr(String str, int subSLength)
- throws UnsupportedEncodingException{
- if (str == null)
- return "";
- else{
- int tempSubLength = subSLength;//截取字节数
- String subStr = str.substring(0, str.length()<subSLength ? str.length() : subSLength);//截取的子串
- int subStrByetsL = subStr.getBytes("GBK").length;//截取子串的字节长度
- //int subStrByetsL = subStr.getBytes().length;//截取子串的字节长度
- // 说明截取的字符串中包含有汉字
- while (subStrByetsL > tempSubLength){
- int subSLengthTemp = --subSLength;
- subStr = str.substring(0, subSLengthTemp>str.length() ? str.length() : subSLengthTemp);
- subStrByetsL = subStr.getBytes("GBK").length;
- //subStrByetsL = subStr.getBytes().length;
- }
- return subStr;
- }
- }
此处采用的是GBK字节截取,英文数字算一个字节,汉字和符号算2个字节。