Created
July 31, 2012 02:58
-
-
Save fankay/3213142 to your computer and use it in GitHub Desktop.
PinYin4J的用法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void main(String[] args){ | |
String str = "凯盛软件"; | |
System.out.println(stringToPinYin(str)); | |
} | |
public static String charToPinYin(char c) { | |
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat(); | |
format.setCaseType(HanyuPinyinCaseType.LOWERCASE); //设置大小写 | |
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); //不输出音调 | |
format.setVCharType(HanyuPinyinVCharType.WITH_V); //拼音中的u输出为v 例如lv | |
try { | |
//返回汉字的拼音,如果为多音字则返回所有读音 | |
String[] result = PinyinHelper.toHanyuPinyinStringArray(c,format); | |
if(result == null) { | |
return null; //如果传入的不是汉字,例如A,则返回数组为null | |
} else { | |
return result[0]; //返回汉字的第一个读音 | |
} | |
} catch (BadHanyuPinyinOutputFormatCombination e) { | |
e.printStackTrace(); | |
return null; | |
} | |
} | |
public static String stringToPinYin(String str) { | |
StringBuilder sb = new StringBuilder(); | |
for(int i = 0;i < str.length();i++) { | |
char c = str.charAt(i); | |
if(charToPinYin(c) == null) { | |
sb.append(c); | |
} else { | |
sb.append(charToPinYin(c)); | |
} | |
} | |
return sb.toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment