Skip to Main Content

Chinese

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

[原创]精确截取字符串

702619Oct 18 2004 — edited May 22 2006
开发中经常遇到,字符串过长,无法完全显示的问题

这时候就需要截取我们所需要的长度,后面显示省略号或其他字符。

由于中文字符占两个字节,而英文字符占用一个字节,所以,单纯地判断字符数,效果往往不尽如人意

下面的方法通过判断字符的类型来进行截取,效果还算可以:)


如果大家有其他的解决方法欢迎贴出来,共同学习:)
**********************************************************************
private String str;
private int counterOfDoubleByte;
private byte b[];
/**
* 设置需要被限制长度的字符串
* @param str 需要被限制长度的字符串
*/
public void setLimitLengthString(String str){
this.str = str;
}
/**
* @param len 需要显示的长度(<font color="red">注意:长度是以byte为单位的,一个汉字是2个byte</font>)
* @param symbol 用于表示省略的信息的字符,如“...”,“>>>”等。
* @return 返回处理后的字符串
*/
public String getLimitLengthString(int len, String symbol) throws UnsupportedEncodingException {
counterOfDoubleByte = 0;
b = str.getBytes("gb2312");
if(b.length <= len)
return str;
for(int i = 0; i < len; i++){
if(b < 0)
counterOfDoubleByte++;
}

if(counterOfDoubleByte % 2 == 0)
return new String(b, 0, len, "gb2312") + symbol;
else
return new String(b, 0, len - 1, "gb2312") + symbol;
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 19 2006
Added on Oct 18 2004
68 comments
10,211 views