java实现中英文混合字符截取方法

Submitted by kinglong on 2006-7-21 0:17:28
java实现中英文混合字符截取方法(按字节长度截取,中文字符是占两个字节的,英文字符是占一个字节的)
public class Tools {
     public Tools() {
     }

     /**
      * 字符串按字节截取
      * @param str 原字符
      * @param len 截取长度
      * @return String
      * @author kinglong
      * @since 2006.07.20
      */
      public static String splitString(String str, int len) {
             return splitString(str, len, "...");
      }

      /**
       * 字符串按字节截取
       * @param str 原字符
       * @param len 截取长度
       * @param elide 省略符
       * @return String
       * @author kinglong
       * @since 2006.07.20
       */
       public static String splitString(String str,int len,String elide) {
              if (str == null) {
                     return "";
              }
              byte[] strByte = str.getBytes();
              int strLen = strByte.length;
              int elideLen = (elide.trim().length() == 0) ? 0 : elide.getBytes().length;
              if (len >= strLen || len < 1) {
                     return str;
              }
              if (len - elideLen > 0) {
                     len = len - elideLen;
              }
              int count = 0;
              for (int i = 0; i < len; i++) {
                     int value = (int) strByte[i];
                     if (value < 0) {
                            count++;
                     }
              }
              if (count % 2 != 0) {
                     len = (len == 1) ? len + 1 : len - 1;
              }
              return new String(strByte, 0, len) + elide.trim();
       }
}