java 生成拼音_java 根据汉字生成拼音全拼或拼音首字母

1.情景展示

java 根据中文生成对应的拼音

2.准备工作

所需jar包:pinyin4j-2.5.0.jar

3.解决方案

导包

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;

代码实现

/**

* 根据汉字生成拼音全拼或拼音首字母

* @explain

* @author Marydon

* @creationTime 2020年5月14日下午4:26:30

* @version 1.0

* @since

* @email marydon20170307@163.com

*/

public class GetPinyin {

/**

* 得到全拼

* @param str

* @return 全拼(小写)

*/

public static String getPinYin(String str){

char t1[]=null;

t1=str.toCharArray();

String[] t2=new String[t1.length];

HanyuPinyinOutputFormat t3=new HanyuPinyinOutputFormat();

t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);

t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

t3.setVCharType(HanyuPinyinVCharType.WITH_V);

String t4="";

int t0=t1.length;

try {

for ( int i = 0; i < t0; i++ ) {

//是用来判断是不是中文的一个条件,采用的是unicode编码

if(Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")){

t2= PinyinHelper.toHanyuPinyinStringArray(t1[i],t3);

t4+=t2[0];

}else {

t4+=Character.toString(t1[i]);

}

}

return t4;

} catch ( BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination ) {

badHanyuPinyinOutputFormatCombination.printStackTrace();

}

return t4;

}

/**

* 得到汉字首字母的拼音

* @param str

* @return 拼音首字母(大写)

*/

public static String getPinYinHeaderChar(String str){

String convert="";

for ( int i = 0; i < str.length(); i++ ) {

char word=str.charAt(i);

String[] pinYinArray=PinyinHelper.toHanyuPinyinStringArray(word);

if ( pinYinArray!=null ){

convert+=pinYinArray[0].charAt(0);

}else {

convert+=word;

}

}

return convert.toUpperCase();

}

//测试

public static void main(String[] args) {

System.out.println(getPinYin("火影忍者Marydon"));

System.out.println(getPinYinHeaderChar("海贼王"));

}

}

4.效果展示

e505b047687bf6392c20991448f7a9dc.png

写在最后

哪位大佬如若发现文章存在纰漏之处或需要补充更多内容,欢迎留言!!!

相关推荐:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值