About pinyin4j

来源:互联网 发布:数据库属性类型有哪些 编辑:程序博客网 时间:2024/06/04 18:11

You could get the first character of every Chinese word by the following code:

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.exception.BadHanyuPinyinOutputFormatCombination;


public class Test {


/**
* @param args
*/
public static void main(String[] args) {
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));
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
pybf.append(arr[i]);
}
}
System.out.println(pybf.toString().replaceAll("\\W", "").trim());
}

}


Result: stalb