Package com. jframe. kit;
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;
/**
* Chinese character conversion characters: Chinese pinyin; English characters remain unchanged
* @ Author xuke
*
*/
Public class Cn2SpellKit {
/**
* Chinese characters are converted to the first letter of the Chinese pinyin alphabet. The English characters remain unchanged.
* @ Param chines Chinese Characters
* @ Return pinyin
*/
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 (nameChar [I] & gt; 128 ){
Try {
PinyinName + = PinyinHelper. toHanyuPinyinStringArray (nameChar [I], defaultFormat) [0]. charAt (0 );
} Catch (BadHanyuPinyinOutputFormatCombination e ){
E. printStackTrace ();
}
} Else {
PinyinName + = nameChar [I];
}
}
Return pinyinName;
}
/**
* Chinese character conversion characters: Chinese pinyin; English characters remain unchanged
* @ Param chines Chinese Characters
* @ Return pinyin
*/
Public static String converterToSpell (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 (nameChar [I] & gt; 128 ){
Try {
PinyinName + = PinyinHelper. toHanyuPinyinStringArray (nameChar [I], defaultFormat) [0];
} Catch (BadHanyuPinyinOutputFormatCombination e ){
E. printStackTrace ();
}
} Else {
PinyinName + = nameChar [I];
}
}
Return pinyinName;
}
Public static String spell (String name ){
String pinyinName = "";
If (name! = Null &&! "". Equals (name )){
If (name. length () <= 2 ){
PinyinName = converterToSpell (name );
} Else {
PinyinName = converterToSpell (name. substring (0, 1) + converterToFirstSpell (name. substring (1, name. length ()));
}
}
Return pinyinName;
}
Public static void main (String [] args ){
System. out. println (spell ("Yang Cheng "));
System. out. println (spell ("Wang Shuai (small)"). toUpperCase ());
}
}
Pinyin4j-2.5.0.jar required