(Android) Chinese Character

时间:2022-04-04 22:57:45

Convert Chinese strings to English strings

Apply pinyin4j.jar

public static class ConvertChineseToPinyin {

public static String getPingYin(String src) {
   char[] t1 = null;
   t1 = src.toCharArray();
   String[] t2 = new String[t1.length];
   HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
   t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
   t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
   t3.setVCharType(HanyuPinyinVCharType.WITH_V);
   String t4 = "";
   int t0 = t1.length;
   try {
    for (int i = 0; i < t0; i++) {
     if (java.lang.Character.toString(t1[i]).matches(
       "[\\u4E00-\\u9FA5]+")) {
      t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);
      t4 += t2[0];
     } else {
      t4 += java.lang.Character.toString(t1[i]);
     }
    }
    return t4;
   } catch (Exception e) {
    e.printStackTrace();
   }
   return t4;
  }

public static String cn2FirstSpell(String chinese) {
   StringBuffer pybf = new StringBuffer();
   char[] arr = chinese.toCharArray();
   HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
   defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
   defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
   for (int i = 0; i < arr.length; i++) {
    if (arr[i] > 128) {
     try {
      String[] _t = PinyinHelper.toHanyuPinyinStringArray(
        arr[i], defaultFormat);
      if (_t != null) {
       pybf.append(_t[0].charAt(0));
      }
     } catch (Exception e) {
      e.printStackTrace();
     }
    } else {
     pybf.append(arr[i]);
    }
   }
   return pybf.toString().replaceAll("\\W", "").trim();

}
 }

Android API for sorting Chinese strings

Comparator comparator = Collator
     .getInstance(java.util.Locale.CHINA);
   Collections.sort(userRealNames, comparator);

//userRealNames is ArrayList<String>

Check Chinese characters

private static final boolean isChinese(char c) {
  Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
  if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
    || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
    || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
    || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
    || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
    || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
   return true;
  }
  return false;
 }