Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Android 获取汉字拼音

Android提供了汉字转拼音的类。但是这个类是在联系人app下的。具体目录是packages/providers/ContactsProvider/src/com/android/providers/contacts的HanziToPinyin.java文件。如果想要这个工具类,可以直接拷贝来用。 获取一段汉字全拼方法:
  1.  public String getFullPinYin(String source){  
  2.   
  3.      if (!Arrays.asList(Collator.getAvailableLocales()).contains(Locale.CHINA)) {  
  4.   
  5.          return source;  
  6.   
  7.      }   
  8.   
  9.      ArrayList<Token> tokens = HanziToPinyin.getInstance().get(source);  
  10.   
  11.      if (tokens == null || tokens.size() == 0) {  
  12.   
  13.         return source;  
  14.   
  15.      }  
  16.   
  17.      StringBuffer result = new StringBuffer();  
  18.   
  19.      for (Token token : tokens) {  
  20.   
  21. if (token.type == Token.PINYIN) {  
  22.   
  23.     result.append(token.target);  
  24.   
  25. else {  
  26.   
  27.     result.append(token.source);  
  28.   
  29. }  
  30.   
  31.   
  32.   
  33.      return result.toString();  
  34.   
  35.  }  
获取一段汉字简拼的方法:
  1.  public String getFirstPinYin(String source){  
  2.   
  3.      if (!Arrays.asList(Collator.getAvailableLocales()).contains(Locale.CHINA)) {  
  4.   
  5.          return source;  
  6.   
  7.      }   
  8.   
  9.      ArrayList<Token> tokens = HanziToPinyin.getInstance().get(source);  
  10.   
  11.      if (tokens == null || tokens.size() == 0) {  
  12.   
  13.         return source;  
  14.   
  15.      }  
  16.   
  17.      StringBuffer result = new StringBuffer();  
  18.   
  19.      for (Token token : tokens) {  
  20.   
  21. if (token.type == Token.PINYIN) {  
  22.   
  23.     result.append(token.target.charAt(0));  
  24.   
  25. else {  
  26.   
  27.     result.append("#");  
  28.   
  29. }  
  30.   
  31.   
  32.   
  33.      return result.toString();  
  34.   
  35.  }  
举例:
  1. String str = "我是中国人";  
  2. getFullPinYin(str);    //返回的是 WOSHIZHONGGUOREN   
  3. getFirstPinYin(str);    //返回的是WSZGR  
更多Android相关信息见Android 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=11