java实现中英文混合字符截取方法(按字节长度截取,中文字符是占两个字节的,英文字符是占一个字节的)
PS:这个方法可能不是最优化的,但基本能解决中英文混合字符截取问题了,如果你有更好的方法,可以发邮件(txyhl@126.com)给我!
public
class
Tools {
public Tools() {
}
/**
* 字符串按字节截取
* @param str 原字符
* @param len 截取长度
* @return String
* @author kinglong
* @since 2006.07.20
*/
public static String splitString(String str, int len) {
return splitString(str, len, " ... " );
}
/**
* 字符串按字节截取
* @param str 原字符
* @param len 截取长度
* @param elide 省略符
* @return String
* @author kinglong
* @since 2006.07.20
*/
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;
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();
}
}
public Tools() {
}
/**
* 字符串按字节截取
* @param str 原字符
* @param len 截取长度
* @return String
* @author kinglong
* @since 2006.07.20
*/
public static String splitString(String str, int len) {
return splitString(str, len, " ... " );
}
/**
* 字符串按字节截取
* @param str 原字符
* @param len 截取长度
* @param elide 省略符
* @return String
* @author kinglong
* @since 2006.07.20
*/
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;
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();
}
}