limited Chinese string Length - Android Internationalization

Android examples for Internationalization:Chinese

Description

limited Chinese string Length

Demo Code

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

public class Main {

  public static String limitedChineseCharLength(String value, float chineseCharLength) {
    int length = value.length();
    int index = (int) chineseCharLength;
    while (getChineseCharLength(value.substring(0, index)) < chineseCharLength && index < length) {
      index++;/* w  ww  .  j  a v  a2 s . c  o m*/
    }
    return value.substring(0, index);
  }

  private static String chineseEx = "[\\u4e00-\\u9fa5]";

  public static float getChineseCharLength(String value) {
    float count = 0;
    Pattern p = Pattern.compile(chineseEx);
    Matcher m = p.matcher(value);
    while (m.find()) {
      for (int i = 0; i <= m.groupCount(); i++) {
        count++;
      }
    }
    count += 0.5f * (value.length() - count);
    return count;
  }
}

Related Tutorials