欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

中文转拼音【pinyin4j使用】 博客分类: 编程  

程序员文章站 2024-03-22 09:02:28
...
/**
* 汉字转汉语拼音首字母,英文字符不变
*
* @param chinese
* @return
*/
public static String pinyinFirst(String chinese) {
String retVal = "";
char[] chineses = chinese.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < chineses.length; i++) {
if (chineses[i] > 128) {
try {
retVal += PinyinHelper.toHanyuPinyinStringArray(chineses[i], defaultFormat)[0].charAt(0);
} catch (BadHanyuPinyinOutputFormatCombination e) {
log.error(e, e);
}
} else {
retVal += chineses[i];
}
}
return retVal;
}


/**
* 汉字转汉语拼音,英文字符不变
*
* @param chinese
* @return
*/
public static String pinyinFull(String chinese) {
String retVal = "";
char[] chineses = chinese.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < chineses.length; i++) {
if (chineses[i] > 128) {
try {
retVal += PinyinHelper.toHanyuPinyinStringArray(chineses[i], defaultFormat)[0];
} catch (BadHanyuPinyinOutputFormatCombination e) {
log.error(e, e);
}
} else {
retVal += chineses[i];
}
}
return retVal;
}