|
java实现中英文混合字符截取方法(按字节长度截取,中文字符是占两个字节的,英文字符是占一个字节的)
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;
if (value < 0) {
count++;
}
}
if (count % 2 != 0) {
len = (len == 1) ? len + 1 : len - 1;
}
return new String(strByte, 0, len) + elide.trim();
}
public static void main(String args[]){
String s="I am a student.我是一个学生";
System.out.println(Tools.splitString(s,24));
System.out.println(Tools.splitString(s,23));
System.out.println(Tools.splitString(s,25));
System.out.println(Tools.splitString(s,26));
}
}
运行结果:
C:\test>java Tools
I am a student.我是一...
I am a student.我是...
I am a student.我是一...
I am a student.我是一个... |
|