Java將中文姓名轉換為拼音

來源:互聯網
上載者:User

代碼如下:

 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 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.