get Chinese String Sub String - Android Internationalization

Android examples for Internationalization:Chinese

Description

get Chinese String Sub String

Demo Code

public class Main {

  public static String getSubString(String text, int length) {
    return getSubString(text, length, true);
  }//from   w ww.  j  a  v a2  s.  c o m

  public static String getSubString(String text, int length, boolean isOmit) {

    StringBuffer sb = new StringBuffer();
    String Reg = "^[\u4e00-\u9fa5]{1}$";
    int result = 0;
    for (int i = 0; i < text.length(); i++) {
      String b = Character.toString(text.charAt(i));
      if (b.matches(Reg)) {
        result += 2;
      } else {
        result++;
      }

      if (result <= length + 1) {
        sb.append(b);
      } else {
        if (isOmit) {
          sb.append("...");
        }
        break;
      }
    }
    return sb.toString();
  }

}

Related Tutorials