汉字转拼音的工具类
平常是处理文字的时候更多用到的是字符串方面的工具类,作为学习汉字的工具,拼音还是很重要的一个辅助方式,分享一个汉字转拼音的工具类。可以用于帮助学习汉字或者作为一些汉字的辅助说明都也是可以的。这个还支持将汉字拼音输出为首字母,例如"愷龍"可以输出为"kl",在现在大家很多时候都用缩写的情况下,可以也可以作为一个辅助的工具。
该工具类用到了pinyin4j-2.5.0.jar包
包下载地址:
网盘下载:https://kohler.lanzouv.com/i3bQG0g2imkj
Maven中央库:https://mvnrepository.com/artifact/org.clojars.cbilson/pinyin4j/2.5.0
完整代码:
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 GetPinyin {
/**
* 得到 全拼
* @Param src
* @return
*/
public static String getPingYin(String src) {
char[] t1 = null;
t1 = src.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);
StringBuffer t4 = new StringBuffer();
int t0 = t1.length;
try {
for (char c : t1) {
// 判断是否为汉字字符
if (Character.toString(c).matches(
"[\\u4E00-\\u9FA5]+")) {
t2 = PinyinHelper.toHanyuPinyinStringArray(c, t3);
t4.append(t2[0]);
} else {
t4.append(Character.toString(c));
}
}
return t4.toString();
} catch (BadHanyuPinyinOutputFormatCombination e1) {
e1.printStackTrace();
}
return t4.toString();
}
/**
* 得到中文首字母
* @param str
* @return
*/
public static String getPinYinHeadChar(String str) {
StringBuffer convert = new StringBuffer();
for (int j = 0; j < str.length(); j++) {
char word = str.charAt(j);
String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
if (pinyinArray != null) {
convert.append(pinyinArray[0].charAt(0));
} else {
convert.append(word);
}
}
return convert.toString();
}
public static void main(String[] args) {
String cnStr = "快关注愚生浅末";
System.out.println(getPingYin(cnStr));
System.out.println(getPinYinHeadChar(cnStr));
}
}
运行效果:
公众号原文地址:https://mp.weixin.qq.com/s/K0tBRnV0X8yy2OJY5Okt-A
欢迎关注公众号:愚生浅末。

【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库