package com.visystem.vicp.dm.util;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- 汉字转换位汉语拼音,英文字符不变
*/
public class Cn2SpellUtil {
/** 日志输出 */
private static final Logger logger = LoggerFactory.getLogger(Cn2SpellUtil.class);
private static String CNSPELL=",.、,”“ ";
private static String CNCHAR="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、? ]";
/**
* 汉字转换位汉语拼音首字母,英文字符不变
* @param chines 汉字
* @return 拼音
*/
public static String converterToFirstSpell(String chines){
String pinyinName = "" ;
char [] nameChar = chines.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for ( int i = 0 ; i < nameChar.length; i ++ ) {
if(CNCHAR.indexOf(nameChar[i])==-1){
if (nameChar[i] > 128 ) {
try {
pinyinName += PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[ 0 ].charAt( 0 );
} catch (BadHanyuPinyinOutputFormatCombination e) {
logger.error("出现异常", e);
}
} else {
pinyinName += nameChar[i];
}
}
}
return pinyinName;
}
/**
* 汉字转换位汉语拼音,英文字符不变
* @param chines 汉字
* @return 拼音
*/
public static String converterToSpell(String chines){
String pinyinName = "" ;
try {
char [] nameChar = chines.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for ( int i = 0 ; i < nameChar.length; i ++ ) {
if(CNCHAR.indexOf(nameChar[i])==-1){
if (nameChar[i] > 128 ) {
pinyinName += PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[ 0 ];
} else {
pinyinName += nameChar[i];
}
}
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
logger.error("出现异常", e);
}
return pinyinName;
}
/**
* 判断是否为中文
* @param c
* @return
*/
private static final boolean isChinese(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
return true;
}
return false;
}
public static void main(String[] args) {
System.out.println(converterToSpell("欢迎来到最棒的Java ,“”,,中文社区"));
}
}