package cap1;
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 chines 汉字
* @return 拼音
*/
public static String converterToFirst(String chines) {
String pinyinName = "";
char[] nameChar = chines.toCharArray();//转换成字符数组
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();//定义pinyin格式
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);//小写字母
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);//不要声调
//取得字符串第一个汉字的首字母的第一个,就是取多音字的第一个
if (nameChar[0] > 128) {
try {
pinyinName += PinyinHelper.toHanyuPinyinStringArray(nameChar[0], defaultFormat)[0].charAt(0);
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
}
return pinyinName;
}
/**
* 汉字转换位汉语拼音首字母,英文字符不变
* @param chines 汉字
* @return 拼音
*/
public static String converterToFirstSpell(String chines) {
String pinyinName = "";
char[] nameChar = chines.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < nameChar.length; i++) {
if (nameChar[i] > 128) {
try {
pinyinName += PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[0].charAt(0);
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
pinyinName += nameChar[i];
}
}
return pinyinName;
}
/**
* 汉字转换位汉语拼音,英文字符不变
* @param chines 汉字
* @return 拼音
*/
public static String converterToSpell(String chines) {
String pinyinName = "";
char[] nameChar = chines.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < nameChar.length; i++) {
if (nameChar[i] > 128) {
try {
pinyinName += PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[0];
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
pinyinName += nameChar[i];
}
}
return pinyinName;
}
public static void main(String[] args) {
System.out.println(converterToFirst("行欢迎来到最棒的Java中文学院"));
System.out.println(converterToFirstSpell("行欢迎来到最棒的Java中文学院"));
System.out.println(converterToSpell("行欢迎来到最棒的Java中文学院"));
}
}