/**
* 字符串按字节截取
* @param str 原字符
* @param len 截取长度
* @return String
* @author ivan
* @since 2010.07.05
*/
public static String splitString(String str, int len) {
return splitString(str, len, "...");
}
/**
* 字符串按字节截取
* @param str 原字符
* @param len 截取长度
* @param elide 省略符
* @return String
* @author ivan
* @since 2010.07.05
*/
public static String splitString(String str,int len,String elide) {
if (str == null) {
return "";
}
byte[] strByte = str.getBytes();
int strLen = strByte.length;
//int elideLen = (elide.trim().length() == 0) ? 0 : elide.getBytes().length;
int elideLen = 0;
if (len >= strLen || len < 1) {
return str;
}
if (len - elideLen > 0) {
len = len - elideLen;
}
int count = 0;
for (int i = 0; i < len; i++) {
int value = (int) strByte[i];
if (value < 0) {
count++;
}
}
if (count % 2 != 0) {
len = (len == 1) ? len + 1 : len - 1;
}
return new String(strByte, 0, len) + elide.trim();
}
转
http://blgaici1.iteye.com/blog/723255
public static String subStr(String str, int num) {
int max = num;
try {
max = trimGBK(str.getBytes("GBK"),num);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
int sum = 0;
if (str != null && str.length() > max) {
StringBuilder sb = new StringBuilder(max);
for (int i = 0; i < str.length(); i++) {
int c = str.charAt(i);
//if ((c & 0xff00) != 0)
//sum += 2;
//else
sum += 1;
if (sum <= max)
sb.append((char) c);
else
break;
}
return sb.append("...").toString();
} else
return str != null ? str : "";
}
public static int trimGBK(byte[] buf,int n){
int num = 0;
boolean bChineseFirstHalf = false;
if(buf.length < n )return buf.length;
for(int i=0;i
{
if(buf[i]<0 && !bChineseFirstHalf){
bChineseFirstHalf = true;
}else{
num++;
bChineseFirstHalf = false;
}
}
return num;
}