中文转拼音【pinyin4j使用】

/**
* 汉字转汉语拼音首字母,英文字符不变
*
* @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;
}

你可能感兴趣的:(编程)