安字節截取字符串

package cn.ilex.demo;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SplitString {


   public static void main(String[] args) throws IOException {

    String s = "我ABC漢DEF";
                
    System.out.println(getStr(s,4));

  }
  
   public static String getStr(String str, int bytes){
    String _str="";
     int count=0;
    Pattern p= Pattern.compile( "[\\u4e00-\\u9fa5]");
     char[] c=str.toCharArray();
     for ( int i=0;i<c.length;i++){
      String s= new String(c,i,1);
      Matcher m=p.matcher(s);
       if (m.find()){
        count+=2;
      } else
        count+=1;
       if (count<=bytes){
        _str=_str+s;
      } else
         break;
    }
     return _str;
  }
  
  
         /**
         * 截取字符串,並在截取的字符串後添加指定後綴,若是字符串長度小於指定長度時不添加後綴
         * 原樣返回。
         *
         * @param str            須要截取的字符串
         * @param length     截取字符串的長度,字母算 1 個字,全角字符算 2 個字
         * @param suffix     超出時添加的後綴
         * @return
         */

         public static String truncate(String str, int length, String suffix) {
                 if((str == null) || (str.length() == 0) || (length < 1)) {
                         return str;
                }
                 char[] chs = str.toCharArray();
                 int len = 0;
                 int offset = 0;
                 for( int i = 0; i < chs.length; i++, offset++) {
                        len += (chs[i] > 0xff) ? 2 : 1;
                         if(len > length) {
                                 break;
                        }
                }
                 if(offset == chs.length) {
                         return str;
                }
                 if(suffix == null || suffix.trim().length() == 0) {
                         return new String(chs, 0, offset);
                }
                 return new String(chs, 0, offset) + suffix.trim();         } }
相關文章
相關標籤/搜索