汉字转拼音的工具类
来源:互联网 发布:linux网卡速率命令 编辑:程序博客网 时间:2024/04/28 13:38
介绍3个方法:汉字转换为拼音、获取每个汉字的首字母、获取第一个汉字的首字母(如果是姓名,即姓的首字母),代码如下:
PinYinUtil:
package com.home;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;/** * 拼音转换工具类 * * @author Administrator * */public class PinYinUtil {/** * 将字符串中的中文转化为拼音,其他字符不变 * * @param inputStr * @return */public static String getPinYin(String inputStr) {HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();format.setCaseType(HanyuPinyinCaseType.LOWERCASE);format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);format.setVCharType(HanyuPinyinVCharType.WITH_V);char[] input = inputStr.trim().toCharArray();String output = "";try {if (input != null) {for (char c : input) {if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {String[] temp = PinyinHelper.toHanyuPinyinStringArray(c, format);output += temp[0];} else {output += Character.toString(c);}}}} catch (BadHanyuPinyinOutputFormatCombination e) {}return output;}/** * 得到每个汉字首字母,英文字符不变 * * @param chineseStr * @return */public static String getFirstSpell(String chineseStr) {StringBuffer sb = new StringBuffer();char[] input = chineseStr.toCharArray();HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();format.setCaseType(HanyuPinyinCaseType.LOWERCASE);format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);if (input != null) {for (char c : input) {if (c > 128) {try {String[] temp = PinyinHelper.toHanyuPinyinStringArray(c, format);if (temp != null) {sb.append(temp[0].charAt(0));}} catch (BadHanyuPinyinOutputFormatCombination e) {e.printStackTrace();}} else {sb.append(c);}}}return sb.toString().replaceAll("\\W", "").trim();}/** * 获取姓名中姓的首字母 * * @param chineseStr * @param isUpper * 是否转换为大写字母 * @return */public static String getFirstLetter(String chineseStr, boolean isUpper) {String pinyin = getPinYin(chineseStr);String firstLetter = pinyin.substring(0, 1);if (isUpper) {firstLetter = firstLetter.toUpperCase();} else {firstLetter = firstLetter.toLowerCase();}return firstLetter;}}
拼音转换需要用到的jar包地址:http://download.csdn.net/detail/u010142437/7107529
0 0
- 汉字转拼音的工具类
- 汉字转拼音的工具类
- 汉字转拼音工具类
- 汉字转拼音工具类
- 汉字转拼音工具类
- 汉字与拼音互转的工具类
- 将汉字转成拼音的工具类
- pinyin4j汉字转换拼音的工具类
- 获得汉字拼音首字母的工具类
- Java汉字转拼音工具类
- Java汉字转拼音工具类
- Android汉字转拼音工具类
- Android 汉字转拼音工具类
- java汉字转拼音工具类源代码
- java【工具类】汉字转拼音,
- Java 汉字转拼音工具类
- Java汉字转拼音工具类
- Java汉字转拼音工具类
- 成功路上并不拥挤,因为坚持的人不多
- C++PRIMER PLUS第六版课后编程答案 5.1-5.5
- iOS OC面试题
- HTML5学习小结
- MongoDB与内存
- 汉字转拼音的工具类
- 从spring容器中获取已经创建好的对象
- 汉字字词转拼音接口(支持多音字)
- C#中使用lock和using语法
- 将字节数组存放到oracle中的blob中
- Tomcat启动时不加载所有项目,而是选择加载项目
- Linux 下 popen 函数引起的僵尸进程 defunct 以及解决办法
- 用C++编写动态库应该遵循的几个指导意见
- 事件查看器