package cn.jfinalbbs.utils;
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.exception.BadHanyuPinyinOutputFormatCombination;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 汉字的帮助类
* Created by yahui on 2015/10/14.
*/
public class ChineseUtils {
public static boolean isChineseChar(String str){
boolean flag = false;
Pattern p=Pattern.compile("[\u4e00-\u9fa5]");
Matcher m=p.matcher(str);
if(m.find()){
flag = true;
}
return flag;
}
public static void main(String[] str) throws BadHanyuPinyinOutputFormatCombination {
System.out.print(String.valueOf('B').toLowerCase());
}
/**
* 默认返回大写
* @param chinese
* @return
* @throws BadHanyuPinyinOutputFormatCombination
*/
public static String toPinyin(String chinese) throws BadHanyuPinyinOutputFormatCombination {
final HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
StringBuffer stringBuffer=new StringBuffer();
if(StrUtil.notBlank(chinese)){
char[] chars=chinese.toCharArray();
for(char item:chars){
boolean flag=ChineseUtils.isChineseChar(item+"");
if(flag){
stringBuffer.append(PinyinHelper.toHanyuPinyinStringArray(item,format)[0]);
}else{
stringBuffer.append(String.valueOf(item).toLowerCase());
}
}
}
return stringBuffer.toString();
}
}