java 实现中文转化为拼音代码 汉字转化为拼音源码分享
对于我们WEB开发者,经常会用到把中文转化为拼音的功能, 下面我分享一下总结的代码:
需要导入lib pinyin4j-2.5.0.jar
public static Set<String> getPinyin(String src) { if (src != null && !src.trim().equalsIgnoreCase("")) { char[] srcChar; srcChar = src.toCharArray(); // 汉语拼音格式输出类 HanyuPinyinOutputFormat hanYuPinOutputFormat = new HanyuPinyinOutputFormat(); // 输出设置,大小写,音标方式等 hanYuPinOutputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE); hanYuPinOutputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); hanYuPinOutputFormat.setVCharType(HanyuPinyinVCharType.WITH_V); String[][] temp = new String[src.length()][]; for (int i = 0; i < srcChar.length; i++) { char c = srcChar[i]; // 是中文或者a-z或者A-Z转换拼音(我的需求,是保留中文或者a-z或者A-Z) if (String.valueOf(c).matches("[\\u4E00-\\u9FA5]+")) { try { temp[i] = PinyinHelper.toHanyuPinyinStringArray( srcChar[i], hanYuPinOutputFormat); } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } } else if (((int) c >= 65 && (int) c <= 90) || ((int) c >= 97 && (int) c <= 122)) { temp[i] = new String[] { String.valueOf(srcChar[i]) }; } else { temp[i] = new String[] { "" }; } } String[] pingyinArray = Exchange(temp); Set<String> pinyinSet = new HashSet<String>(); for (int i = 0; i < pingyinArray.length; i++) { pinyinSet.add(pingyinArray[i]); } return pinyinSet; } return null; }
相关推荐
瓜牛呱呱 2020-11-12
柳木木的IT 2020-11-04
yifouhu 2020-11-02
lei0 2020-11-02
源码zanqunet 2020-10-28
源码zanqunet 2020-10-26
一叶梧桐 2020-10-14
码代码的陈同学 2020-10-14
lukezhong 2020-10-14
lzzyok 2020-10-10
anchongnanzi 2020-09-21
clh0 2020-09-18
changcongying 2020-09-17
星辰大海的路上 2020-09-13
abfdada 2020-08-26
mzy000 2020-08-24
shenlanse 2020-08-18
zhujiangtaotaise 2020-08-18
xiemanR 2020-08-17