dhz
2022-06-22 935b4b66b99b1f022f82cdaef8e3ef6599afbc72
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package cn.ksource.core.util;
 
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
 
public class PinYinUtil {
 
    public static String getCharacterPinYin(char c){
        String[] pinyin = null;    
        HanyuPinyinOutputFormat format =  new HanyuPinyinOutputFormat();
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        try{
             pinyin = PinyinHelper.toHanyuPinyinStringArray(c, format);
          }catch(BadHanyuPinyinOutputFormatCombination e) {
                   e.printStackTrace();
          }
              // 如果c不是汉字,toHanyuPinyinStringArray会返回null
              if(pinyin == null) return null;
              // 只取一个发音,如果是多音字,仅取第一个发音
              return pinyin[0];   
    }
    
     /**
     * 字符串转拼音
     * @param str
     * @param returnNull true:非汉字返回null,false:非汉字原样返回
     * @return
     * @version V1.0.0
     * @author 杨凯
     * @date Jan 15, 2014 12:05:39 PM
     */
    public static String getStringPinYin(String str,boolean returnNull){
               StringBuilder sb = new StringBuilder();
               String tempPinyin = null;
               for(int i = 0; i < str.length(); ++i){
                        tempPinyin =getCharacterPinYin(str.charAt(i));
                        if(tempPinyin == null){
                                 // 如果str.charAt(i)非汉字,则保持原样
                                 sb.append(str.charAt(i));
                        } else{
                           sb.append(tempPinyin);
                        }
               }
               return sb.toString();
     }
     
     /**
     * 字符串转拼音,获取首字母
     * @param str
     * @param returnNull true:非汉字返回null,false:非汉字原样返回
     * @return
     * @version V1.0.0
     * @author 杨凯
     * @date Jan 15, 2014 12:05:39 PM
     */
     public static String getFirstStringPinYin(String str,boolean returnNull){
         StringBuilder sb = new StringBuilder();
         String tempPinyin = null;
         for(int i = 0; i < str.length(); ++i){
                  tempPinyin =getCharacterPinYin(str.charAt(i));
                  if(tempPinyin == null){
                           // 如果str.charAt(i)非汉字,则保持原样
                           sb.append(str.charAt(i));
                  } else{
                     sb.append(tempPinyin.charAt(0));
                  }
         }
         return sb.toString();
}
    
}