字符串截取

来源:互联网 发布:php 个性化推荐系统 编辑:程序博客网 时间:2024/04/29 20:27
[java] view plain copy
  1. /** 
  2.      * 字符串截取 
  3.      * @param str 
  4.      * @param bytes 
  5.      * @return 
  6.      */  
  7.     public static String strSplit(String str , int bytesLength) throws Exception{    
  8.         if(str == null){  
  9.             return null;  
  10.         }  
  11.         //转换成字符数组  
  12.         char[] sourceChar = str.toCharArray();  
  13.         String temp;   
  14.         List<CharInfo> list = new ArrayList<CharInfo>();  
  15.         CharInfo charInfo = null;       
  16.         char tempChar ;  
  17.         for(int i = 0 ; i < sourceChar.length ; i++){  
  18.             tempChar = sourceChar[i];     
  19.             temp = String.valueOf(tempChar);  
  20.             //构建字符信息(字符,长度)  
  21.             charInfo = new CharInfo(temp.getBytes().length, tempChar);        
  22.             list.add(charInfo);  
  23.         }  
  24.         StringBuffer result = new StringBuffer();  
  25.         int currentLength = 0 ;   
  26.         //遍历字符信息列表,根据目标字节长度返回信息          
  27.         for(CharInfo ci : list){  
  28.             if(null == ci){  
  29.                 continue;  
  30.             }  
  31.             currentLength += ci.getBytesLength();  
  32.             if(currentLength > bytesLength){            
  33.                 return result.toString();    
  34.             }  
  35.             result.append(ci.getValue());       
  36.         }  
  37.         return result.toString();    
  38.     }  
  39.   
  40.   
  41. public class CharInfo {   
  42.     private int bytesLength;  
  43.     private char value;  
  44.       
  45.     public CharInfo(int bytesLength , char value){    
  46.         this.bytesLength = bytesLength;  
  47.         this.value = value;  
  48.     }  
  49.   
  50.     public int getBytesLength() {   
  51.         return bytesLength;  
  52.     }  
  53.     public char getValue() {  
  54.         return value;  
  55.     }  
  56. }  
0 0
原创粉丝点击