Java将中文姓名转换为拼音

代码如下:

 1 import net.sourceforge.pinyin4j.PinyinHelper;
 2 import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
 3 import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
 4 import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
 5 import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
 6 public class SpellHelper {
 7     //将中文转换为英文
 8     public static String getEname(String name)
 9      {
10         HanyuPinyinOutputFormat pyFormat = new        HanyuPinyinOutputFormat();
11          pyFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
12         pyFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
13         pyFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
14 
15         return PinyinHelper.toHanyuPinyinString(name, pyFormat, "");
16     }
17 
18     //姓、名的第一个字母需要为大写
19     public static String getUpEname(String name) {
20         char[] strs = name.toCharArray();
21         String newname = null;
22                 
23         //名字的长度
24         if (strs.length == 2) {    
25                 newname = toUpCase(getEname("" + strs[0])) + " "
26                     + toUpCase(getEname("" + strs[1]));
27         } else if (strs.length == 3) 
28          {
29                newname = toUpCase(getEname("" + strs[0])) + " "
30                     + toUpCase(getEname("" + strs[1] + strs[2]));
31         } 
32        else if (strs.length == 4) 
33        {
34             newname = toUpCase(getEname("" + strs[0] + strs[1])) + " "
35                     + toUpCase(getEname("" + strs[2] + strs[3]));
36         } else 
37         {
38             newname = toUpCase(getEname(name));
39         }
40         return newname;
41     }
42 
43     //首字母大写
44     private static String toUpCase(String str) {
45         StringBuffer newstr = new StringBuffer();
46         newstr.append((str.substring(0, 1)).toUpperCase()).append(
47                 str.substring(1, str.length()));
48 
49         return newstr.toString();
50     }
51     public static void main(String[] args) {
52         System.out.println(getUpEname("李宇春"));
53 
54     }
55 
56 }
posted @ 2012-04-16 03:42  json_chan  阅读(8381)  评论(0编辑  收藏  举报