最近因为在做一个项目要求很多都是英文,所以这就涉及到在页面上截取统一长度时中英文不一样长的问题。网上找了找,搞了个工具类,拿出来记录一下吧。
代码如下:
package com.iflytek.util;
import java.io.UnsupportedEncodingException;
/**
* @author xdwang
*
* @ceate 2012-7-19 下午08:15:11
*
* @description
*
*/
public class ChinaEngLengthHelper {
/**
* @descrption
* @author xdwang
* @create 2012-7-19下午08:15:11
* @param args
*/
public static void main(String[] args) {
String chinaStr = "大家好,我叫王旭东!这是一个解决中英文长度的公用方法。";
String chinaOrEnglishStr = "Hello,我叫王旭东!This is a solution 中英文长度的公用方法。";
String englishStr = "Hello,my name is xdwang! This is a solution to the length of the public methods in both Chinese and English.";
System.out.println(subStrHelper(chinaStr, 10, "..."));
System.out.println(subStrHelper(chinaOrEnglishStr, 10, "..."));
System.out.println(subStrHelper(englishStr, 10, "..."));
}
/**
* @descrption 将给定的字符串按着给定的截取长度截取 <br>
* 注意一个汉字占2个字节
* @author xdwang
* @create 2012-6-29下午03:32:25
* @param text
* 需要截取的字符串
* @param length
* 截取的长度,这里的是汉字length的长度,中英文长度和汉字length长度一致
* @param endWith
* 截取后字符串后缀,一般以...结束
* @return 截取后的字符串
*/
public static String subStrHelper(String text, int length, String endWith) {
int textLength = text.length();
int byteLength = 0;
StringBuffer returnStr = new StringBuffer();
for (int i = 0; i < textLength && byteLength < length * 2; i++) {
String str_i = text.substring(i, i + 1);
if (str_i.getBytes().length == 1) {// 英文
byteLength++;
} else {// 中文
byteLength += 2;
}
returnStr.append(str_i);
}
try {
// getBytes("GBK")每个汉字长2,getBytes("UTF-8")每个汉字长度为3
if (byteLength < text.getBytes("GBK").length) {
returnStr.append(endWith);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return returnStr.toString();
}
}
结果:
大家好,我叫王旭东!... Hello,我叫王旭东!Th... Hello,my name is xdw...
大家从结果上看还是差不多吧。 Ok ,收工