/*
* 1.创建java project
* 2.将项目转变为Maven项目
* 3.pom.xml中导入两个架包
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.1</version>
</dependency>
*4.写一个main方法
*/
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 ChineseToPinyin {
public static void main(String[] args) {
String str = "蓝礼巍";
String resultShort = getCnShort(str);
System.out.println(str + "的拼音首字母是 : " + resultShort);
String result=getCnAll(str);
System.out.println(str + "的拼音是 : " + result);
}
static HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
static {
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
format.setVCharType(HanyuPinyinVCharType.WITH_V);
}
// 取首字母
public static String getCnShort(String str) {
String cnShort = "";
int length = str.length();
for (int i = 0; i < length; i++) {
char c = str.charAt(i);
try {
String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(c, format);
if (pinyin.length > 0) {
cnShort = cnShort + pinyin[0].charAt(0);
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
}
return cnShort;
}
//取拼音
public static String getCnAll(String str){
String cnAll = "";
int length=str.length();
for(int i=0;i<length;i++){
char c = str.charAt(i);
try {
String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(c, format);
cnAll = cnAll + pinyin[0];
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
}
return cnAll;
}
}
中文转拼音
最新推荐文章于 2022-03-28 15:38:11 发布