在web開發中,會遇到這樣一個問題,想讓某個內容全部保持在一定長度範圍內,未超出的行全部顯示,超長的行只允許顯示一定的長度,結尾用省略號代替。
粗想一下,實現這個功能很容易,直接取字符串的長度(用length()方法),如果超出,就用substring()方法截取一段,然後再在結尾處加上省略號。但實際上這樣做是不行的,至少說是某種程度上得不到我們想要的結果,因爲一個英文字母和一個漢字用lenth方法得到的值都是1,這不錯,但是在顯示時,一個漢字佔兩個字母的位置,這樣即使我們截取了指定長度的字符串,但實際顯示起來是參差不齊的。下面是我對這個問題給出的解決方案。
- /**
- * @(#)StringUtil.java
- *
- *
- * @author liangh
- * @version 1.00 2008/11/24
- */
- public class StringUtil{
- public StringUtil() {
- }
- public static void main(String[] args){
- String str="12345 英afa五左,大有枝節一碟sd.sdfas 2008-11-22";
- System.out.println(StringUtil.omitString(str,30));
- str="12345 英afa五左,大有枝節s一碟sd.sdfas 2008-11-22";
- System.out.println(StringUtil.omitString(str,30));
- str="12345 英afa五左,大有枝節a";
- System.out.println(StringUtil.omitString(str,30));
- str="12345 英afa五左,大有枝節基";
- System.out.println(StringUtil.omitString(str,30));
- }
- /*
- * 計算字符串的字節長度(字母數字計1,漢字及標點計2)
- *
- */
- public static int byteLength(String string){
- int count = 0;
- for(int i=0;i<string.length();i++){
- if(Integer.toHexString(string.charAt(i)).length()==4){
- count += 2;
- }else{
- count++;
- }
- }
- return count;
- }
- /*
- * 按指定長度,省略字符串部分字符
- * @para String 字符串
- * @para length 保留字符串長度
- * @return 省略後的字符串
- */
- public static String omitString(String string,int length){
- StringBuffer sb = new StringBuffer();
- if(byteLength(string)>length){
- int count = 0;
- for(int i=0;i<string.length();i++){
- char temp = string.charAt(i);
- if(Integer.toHexString(temp).length()==4){
- count += 2;
- }else{
- count++;
- }
- if(count<length-3){
- sb.append(temp);
- }
- if(count==length-3){
- sb.append(temp);
- break;
- }
- if(count>length-3){
- sb.append(" ");
- break;
- }
- }
- sb.append("...");
- }else{
- sb.append(string);
- }
- return sb.toString();
- }
- }
執行結果是:
12345 英afa五左,大有枝節一...
12345 英afa五左,大有枝節s ...
12345 英afa五左,大有枝節a
12345 英afa五左,大有枝節基