码迷,mamicode.com
首页 > 其他好文 > 详细

Iava 得到中文拼音的方法

时间:2015-07-28 22:44:44      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

 

再实现通讯录的时候,需要把联系人按照A-Z的顺序排列

这里就需要得到每个联系人的吗名字拼音

下面这三个方法很有用处

 

 

 1 /**
 2 * 获取汉字串拼音,英文字符不变 
 3 * @param chinese 汉字串 
 4 * @return 汉语拼音 
 5 */
 6 public static String getFullSpell(String chinese){
 7 StringBuffer pybf = new StringBuffer();
 8 char[] arr = chinese.toCharArray();
 9 
10 HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
11 defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
12 defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
13 defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
14 
15 try {
16 for(int i = 0;i<arr.length;i++){
17 if(arr[i]>128){
18 pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]);
19 }else{
20 pybf.append(arr[i]);
21 }
22 }
23 } catch (BadHanyuPinyinOutputFormatCombination e) {
24 e.printStackTrace();
25 }
26 return pybf.toString();
27 }
28 
29 /**
30 * 获取汉字串拼音首字母,英文字符不变
31 * @param chinese 汉字串 
32 * @return 汉语拼音首字母
33 */
34 public static String getFirstSpell(String chinese){
35 StringBuffer pybf = new StringBuffer();
36 char[] arr = chinese.toCharArray();
37 HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
38 defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
39 defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
40 defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
41 
42 for(int i = 0;i<arr.length;i++){
43 if(arr[i]>128){
44 try {
45 String[] temp = PinyinHelper.toHanyuPinyinStringArray(arr[i],defaultFormat);
46 if(temp!=null){
47 pybf.append(temp[0].charAt(0));
48 }else{
49 pybf.append(arr[i]);
50 }
51 } catch (BadHanyuPinyinOutputFormatCombination e) {
52 e.printStackTrace();
53 }
54 }
55 }
56 return pybf.toString().replaceAll("\\W", "").trim();
57 }
58 
59 /**
60 * 将字符串中的中文转化为拼音,其他字符不变
61 * @param inputString
62 * @return
63 */
64 public static String getPinYin(String inputString){
65 HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
66 format.setCaseType(HanyuPinyinCaseType.LOWERCASE);//小写
67 format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);//不知道这个是什么意思 写完查api看看
68 format.setVCharType(HanyuPinyinVCharType.WITH_V);//ǜ的输出格式设置 ‘ü‘ 输出为 "v" 
69 
70 char[] input = inputString.trim().toCharArray();
71 String output="";
72 
73 try {
74 for(int i = 0; i < input.length; i++){
75 if(java.lang.Character.toString(input[i]).matches("[\\u4E00-\\u9FA5]+")){
76 String[] temp = PinyinHelper.toHanyuPinyinStringArray(input[i],format);
77 output+=temp[0];
78 }else{
79 output+=input[i];
80 }
81 }
82 }catch (Exception e) {
83 e.printStackTrace();
84 }
85 return output;
86 }

 

Iava 得到中文拼音的方法

标签:

原文地址:http://www.cnblogs.com/miscao/p/4684391.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!