java 将汉字转为拼音
作者:互联网
前言:我当时是将文件名得到后,想将文件名字换成pinyin
需要引入的依赖
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>
具体代码如下:
/**
* 汉字转换为拼音
* @author Red
*/
public class Demo {
/**
* 测试main方法
* @param args
*/
public static void main(String[] args) {
System.out.println(ToFirstChar("汉字转换为拼音").toLowerCase()); //转为首字母大写
System.out.println(ToPinyin("汉字转换为拼音"));
int max=100,min=1;
int ran2 = (int) (Math.random()*(max-min)+min);
System.out.println(ran2);
}
/**
* 获取字符串拼音的第一个字母
* @param chinese
* @return
*/
public static String ToFirstChar(String chinese){
String pinyinStr = "";
char[] newChar = chinese.toCharArray(); //转为单个字符
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < newChar.length; i++) {
if (newChar[i] > 128) {
try {
pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0].charAt(0);
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
}else{
pinyinStr += newChar[i];
}
}
return pinyinStr;
}
/**
* 汉字转为拼音
* @param chinese
* @return
*/
public static String ToPinyin(String chinese){
String pinyinStr = "";
char[] newChar = chinese.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < newChar.length; i++) {
if (newChar[i] > 128) {
try {
pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0];
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
}else{
pinyinStr += newChar[i];
}
}
return pinyinStr;
}
}
标签:java,拼音,chinese,pinyinStr,汉字,newChar,defaultFormat,String 来源: https://blog.csdn.net/tengyuxin/article/details/122116862