`
baalwolf
  • 浏览: 344510 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

java截取中英文混合字符串 等宽显示

 
阅读更多
Java代码  收藏代码
  1. import java.io.UnsupportedEncodingException;  
  2.   
  3. public class StringUtil {  
  4.       
  5.     public static String subString(String text, int length, String endWith) {        
  6.         int textLength = text.length();  
  7.         int byteLength = 0;  
  8.         StringBuffer returnStr =  new StringBuffer();  
  9.         for(int i = 0; i<textLength && byteLength < length*2; i++){  
  10.             String str_i = text.substring(i, i+1);   
  11.             if(str_i.getBytes().length == 1){//英文  
  12.                 byteLength++;  
  13.             }else{//中文  
  14.                 byteLength += 2 ;  
  15.             }  
  16.             returnStr.append(str_i);  
  17.         }  
  18.         try {  
  19.             if(byteLength<text.getBytes("GBK").length){//getBytes("GBK")每个汉字长2,getBytes("UTF-8")每个汉字长度为3  
  20.                 returnStr.append(endWith);  
  21.             }  
  22.         } catch (UnsupportedEncodingException e) {  
  23.             e.printStackTrace();  
  24.         }  
  25.         return returnStr.toString();  
  26.     }  


测试: 

Java代码  收藏代码
  1. public static void main(String[] args) {  
  2.                   
  3.         String text = "。发.。篇>所q阿s似hf的f**发千万s";  
  4.         for(int i = 0; i< text.length();i++){  
  5.             String s = StringUtil.subString(text,i+1,"...");  
  6.             System.out.println(s+"--------------------------"+(i+1));  
  7.         }  
  8.           
  9.     }  


结果: 

Java代码  收藏代码
  1. 。...--------------------------1  
  2. 。发...--------------------------2  
  3. 。发.。...--------------------------3  
  4. 。发.。篇...--------------------------4  
  5. 。发.。篇>...--------------------------5  
  6. 。发.。篇>所...--------------------------6  
  7. 。发.。篇>所q阿...--------------------------7  
  8. 。发.。篇>所q阿s...--------------------------8  
  9. 。发.。篇>所q阿s似...--------------------------9  
  10. 。发.。篇>所q阿s似hf...--------------------------10  
  11. 。发.。篇>所q阿s似hf的...--------------------------11  
  12. 。发.。篇>所q阿s似hf的f*...--------------------------12  
  13. 。发.。篇>所q阿s似hf的f**...--------------------------13  
  14. 。发.。篇>所q阿s似hf的f**发...--------------------------14  
  15. 。发.。篇>所q阿s似hf的f**发千...--------------------------15  
  16. 。发.。篇>所q阿s似hf的f**发千万...--------------------------16  
  17. 。发.。篇>所q阿s似hf的f**发千万s--------------------------17  
  18. 。发.。篇>所q阿s似hf的f**发千万s--------------------------18  
  19. 。发.。篇>所q阿s似hf的f**发千万s--------------------------19  
  20. 。发.。篇>所q阿s似hf的f**发千万s--------------------------20  
  21. 。发.。篇>所q阿s似hf的f**发千万s--------------------------21  



结果分析: 
当截取后的字符串里面有奇数个英文字符,且最后一个是中文字符,这时会多出半个汉字长度 
当截取后的字符串里面有偶数个英文字符,且最后一个是英文字符,这时会少出半个汉字长度 

这是正常的

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics