pinyni4j的使用
?
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
?
public class HanziConvertPinyin {
?
/**
* @param args
*/
public static void main(String[] args) {
// char [] t1 ={'中','華','民','國'};
char[] t1 = { '中', '华', '民', '国', '囧' };
String[] t2 = new String[10];
// 宣告輸出的格式
net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
?
t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
t3.setToneType(HanyuPinyinToneType.WITH_TONE_MARK);
?
t3.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
// 取回陣列循環的數量
int t0 = t1.length;
try {
for (int i = 0; i < t0; i++) {
t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);
?
System.err.println(t2[0]);
}
} catch (BadHanyuPinyinOutputFormatCombination e1) {
e1.printStackTrace();
}
System.out.println("-----------------------------------");
String x = "嘅囧誰說壞學生來勼髮視頻裆児";
x = "获取汉字串拼音首字母";
System.out.println(cn2FirstSpell(x));
System.out.println(cn2Spell(x));
?
}
?
/**
* 获取汉字串拼音首字母,英文字符不变
*?
* @param chinese
* ? ? ? ? ? ?汉字串
* @return 汉语拼音首字母
*/
public static String cn2FirstSpell(String chinese) {
StringBuffer pybf = new StringBuffer();
char[] arr = chinese.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < arr.length; i++) {
if (arr[i] > 128) {
try {
String[] _t = PinyinHelper.toHanyuPinyinStringArray(arr[i],
defaultFormat);
if (_t != null) {
pybf.append(_t[0].charAt(0) + "\t");
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
pybf.append(arr[i] + " ");
}
}
return pybf.toString();
}
?
/**
* 获取汉字串拼音,英文字符不变
*?
* @param chinese
* ? ? ? ? ? ?汉字串
* @return 汉语拼音
*/
public static String cn2Spell(String chinese) {
StringBuffer pybf = new StringBuffer();
char[] arr = chinese.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < arr.length; i++) {
if (arr[i] > 128) {
try {
pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i],
defaultFormat)[0] + "\t");
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
?
pybf.append(arr[i]);
}
}
return pybf.toString();
}
?
}
需要pinyni4j的jar支持,一起吧