| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- package com.izouma.immall.utils;
- 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.springframework.stereotype.Component;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- /**
- * pinyin4j汉字转拼音工具类
- *
- * @author
- */
- @Component
- public class PinYinUtil {
- /**
- * 对单个字进行转换
- *
- * @param pinYinStr 需转换的汉字字符串
- * @return 拼音字符串数组
- */
- public static String getCharPinYin(char pinYinStr) {
- if (!isContainChinese(String.valueOf(pinYinStr))) {
- return String.valueOf(pinYinStr);
- }
- //pinyin4j格式类
- HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
- /*
- * 设置需要转换的拼音格式
- * 以天为例
- * HanyuPinyinToneType.WITHOUT_TONE 转换为tian
- * HanyuPinyinToneType.WITH_TONE_MARK 转换为tian1
- * HanyuPinyinVCharType.WITH_U_UNICODE 转换为tiān
- *
- */
- format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
- //拼音字符串数组
- String[] pinyin = null;
- try {
- //执行转换
- pinyin = PinyinHelper.toHanyuPinyinStringArray(pinYinStr, format);
- } catch (BadHanyuPinyinOutputFormatCombination e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- //pinyin4j规则,当转换的符串不是汉字,就返回null
- if (pinyin == null) {
- return null;
- }
- //多音字会返回一个多音字拼音的数组,pinyiin4j并不能有效判断该字的读音
- return pinyin[0];
- }
- /**
- * 对单个字进行转换
- *
- * @param pinYinStr
- * @return
- */
- public static String getStringPinYin(String pinYinStr) {
- StringBuffer sb = new StringBuffer();
- String tempStr = null;
- //循环字符串
- for (int i = 0; i < pinYinStr.length(); i++) {
- tempStr = getCharPinYin(pinYinStr.charAt(i));
- if (tempStr == null) {
- //非汉字直接拼接
- sb.append(pinYinStr.charAt(i));
- } else {
- sb.append(tempStr);
- }
- }
- return sb.toString();
- }
- /**
- * 判断字符串中是否包含中文
- *
- * @param str 待校验字符串
- * @return 是否为中文
- * @warn 不能校验是否为中文标点符号
- */
- public static boolean isContainChinese(String str) {
- Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
- Matcher m = p.matcher(str);
- if (m.find()) {
- return true;
- }
- return false;
- }
- }
|