從字符串中截取等長字節(jié)的Java代碼
更新時間:2013年12月13日 16:41:46 作者:
這篇文章主要介紹了從字符串中截取等長字節(jié)的Java代碼,有需要的朋友可以參考一下
在頁面顯示的時候,有時候文字無法顯示完全,就只能顯示部分文字,但是直接截取就只能截取等長字符串,英文和中文很難處理
所以就寫了下面方法,截取等長字符
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 ) + ".." ;
}
所以就寫了下面方法,截取等長字符
復制代碼 代碼如下:
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 ) + ".." ;
}
相關(guān)文章
Mybatis如何傳入多個參數(shù)的實現(xiàn)代碼
這篇文章主要介紹了Mybatis如何傳入多個參數(shù)的實現(xiàn)代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-12-12Java8新特性之再見Permgen_動力節(jié)點Java學院整理
這篇文章主要介紹了Java8新特性之再見Permgen的相關(guān)知識,非常不錯,具有參考借鑒價值,需要的的朋友參考下吧2017-06-06淺談s:select 標簽中l(wèi)ist存放map對象的使用
下面小編就為大家?guī)硪黄獪\談s:select 標簽中l(wèi)ist存放map對象的使用。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-11-11Java使用FileInputStream流讀取文件示例詳解
這篇文章主要介紹了Java使用FileInputStream流讀取文件示例詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-07-07Java如何將Excel數(shù)據(jù)導入到數(shù)據(jù)庫
這篇文章主要為大家詳細介紹了Java將Excel數(shù)據(jù)導入到數(shù)據(jù)庫的方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10