在頁面顯示的時候,有時候文字無法顯示完全,就只能顯示部分文字,但是直接截取就只能截取等長字符串,英文和中文很難處理
所以就寫了下面方法,截取等長字符
復制代碼代碼如下:
public static void main(String[] args) {
String str = "20120131:《回家》1你好么" ;
System.out.println( subString(str , 10 ) ) ;
}
public static String subString(String str , int len){
len *= 2 ;
byte[]bytes = str.getBytes() ;
if(bytes.length <= len){
return str ;
}
byte[]newBytes = Arrays.copyOf( bytes, len ) ;
int count = 0 ;
for(byte b : newBytes){
if(b < 0){
count++;
}
}
if(count % 2 != 0){
len ++;
newBytes = Arrays.copyOf( bytes, len ) ;
}
return new String( newBytes ) + ".." ;
}