1 package util;
2
3 import net.sourceforge.pinyin4j.PinyinHelper;
4 import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
5 import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
6 import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
7 import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
8
9 /**
10 * <p>汉字转换为汉语拼音,英文字符不变。此类中的方法均为静态方法,可直接调用。如:ChineseToSpell.converterToSpell("中国") <br/>
11 * 下面给出了一些如何使用ChineseToSpell的示例:
12 * * <p><blockquote><pre>
13 * 汉字转换为汉语拼音,英文字符不变
14 * ChineseToSpell.converterToSpell("中国");返回zhongguo
15 *
16 * </pre></blockquote>
17 *
18 */
19 public class ChineseToSpell {
20
21 /**
22 * 汉字转换为汉语拼音,英文字符不变
23 *
24 * @param chines 汉字
25 * @return 汉字所对应的拼音
26 *
27 */
28 public static String converterToSpell(String chines){
29 String pinyinName = "";
30 char[] nameChar = chines.toCharArray();
31 HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
32 defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
33 defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
34 for (int i = 0; i < nameChar.length; i++) {
35 //判断是否为汉字,如果nameChar[i] > 128为汉字
36 if (nameChar[i] > 128) {
37 try {
38 pinyinName += PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[0];
39 } catch (BadHanyuPinyinOutputFormatCombination e) {
40 e.printStackTrace();
41 }
42 }else{
43 pinyinName += nameChar[i];
44 }
45 }
46 pinyinName = pinyinName.replaceAll("u:", "v");
47 return pinyinName;
48 }
49
50 }