标签:
Maven引入依赖:
<dependency> <groupId>com.belerweb</groupId> <artifactId>pinyin4j</artifactId> <version>2.5.0</version> </dependency>
自己封装了一个工具类:
package com.ylmob.yunpay.util.pinyin; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author DJM */ public class HanyuPinyinUtil { Logger logger = LoggerFactory.getLogger(HanyuPinyinUtil.class); private HanyuPinyinUtil(){ } public static HanyuPinyinUtil getInstance(){ return new HanyuPinyinUtil(); } public String toPinyin(String chineseCharacter){ String pinyin = ""; for(Character chara: chineseCharacter.toCharArray()){ logger.info("The character is {}.", chara); Pattern pt = Pattern.compile("[\\u4e00-\\u9fa5]+"); Matcher mt = pt.matcher(chara.toString()); if(mt.matches()){ logger.info("The character {} is match.", chara); HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat(); format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); String[] hyArr = null; try { hyArr = PinyinHelper.toHanyuPinyinStringArray(chara, format); } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } pinyin = pinyin.concat(hyArr[0]); }else{ //过滤空白字符 Pattern blankPt = Pattern.compile("\\s+"); Matcher blankMt = blankPt.matcher(chara.toString()); if(!blankMt.matches()){ pinyin = pinyin.concat(chara.toString()); } } } return pinyin; } }
标签:
原文地址:http://my.oschina.net/dengjianming/blog/497293