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();
        }
}