====================================
带...的字符串截取,保证所有字符长度(中文算2)不超过max:
例:
left("abcdefg", 7)="abcdefg"
left("abcdefg", 6)="abc..."
left("中文abcdefg", 9)="中文ab..."
package com.crackj2ee.util;
/**
* @author Xuefeng, asklxf@163.com
*/
public class StringUtil {
public static String left(String s, int max) {
char[] cs = s.toCharArray();
int count = 0;
int last = cs.length;
for(int i=0; i<cs.length; i++) {
if(cs[ i ]>255)
count+=2;
else
count++;
if(count>max) {
last = i+1;
break;
}
}
if(count<=max) // string is short or just the size!
return s;
// string is too long:
max -= 3;
for(int i=last-1; i>=0; i--) {
if(cs[ i ]>255)
count-=2;
else
count--;
if(count<=max) {
return s.substring(0, i) + "...";
}
}
return "...";
}
}
……
【阅读全文】