パッケージcom.xxx.xxx.xxx。 輸入net.sourceforge.pinyin4j.PinyinHelper; 輸入net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; 輸入net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat。 輸入net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; 輸入java.util.regex.Matcher; 輸入java.util.regex.Patternの; / ** * 2019年12月9日夜03時28分に13375によって作成されました * * @ClassName:com.jxdinfo.hussar.common * @description:1 * @author:lifujian * @date:2019年12月9日夜03時28分 * / パブリッククラスChineseToPinyinUtils { 公共の静的な列挙型{ 大文字、//すべて大文字 LOWERCASE、//すべて小文字 FIRSTUPPER //大文字の } 公共の静的な文字列toPinYin(文字列str){ リターンtoPinYin(STR、 ""、Type.UPPERCASE)。 } 公共の静的な文字列toPinYin(文字列str、文字列spera){ toPinYin(STR、spera、Type.UPPERCASE)を返します。 } / ** * strは音素に変換し、無漢字またはピンインに対応しない場合、変換はないようです *のような:変換MINGTIAN明日 * @Param STR:中国語の文字を変換します * @Param spera:変換結果の区切り文字 * @return * @throws BadHanyuPinyinOutputFormatCombination * / 公共の静的な文字列toPinYin(文字列str、文字列spera、タイプtype){ {試します HanyuPinyinOutputFormat形式=新しいHanyuPinyinOutputFormat()。 IF(STR == NULL || str.trim()。長さ()== 0) 「」を返します。 もし(タイプ== Type.UPPERCASE) format.setCaseType(HanyuPinyinCaseType.UPPERCASE)。 他 format.setCaseType(HanyuPinyinCaseType.LOWERCASE)。 文字列PY = ""; 文字列のTEMP = ""; 文字列[] T。 以下のために(; I <str.length(); INT iが0 = I ++){ チャーC = str.charAt(I)。 IF((INT)C <= 128) PY + = C。 他の{ T = PinyinHelper.toHanyuPinyinStringArray(Cフォーマット) (T == null)の場合 PY + = C。 他の{ TEMP = T [0]。 もし(タイプ== Type.FIRSTUPPER) TEMP = T [0] .toUpperCase()のcharAt(0)+ temp.substring(1)。 文字列パターン= "[\\ D] {1}"; //正規デジタルトーンを除去する、すなわち TEMP = temp.replaceAll(パターン、 ""); PY + =一時+(I == str.length() - 1 "":spera?)。 } } } リターンpy.trim(); }キャッチ(BadHanyuPinyinOutputFormatCombination電子){ e.printStackTrace(); ヌルを返します。 } } }
POMファイル紹介:
<! - ピンインにPinyin4j中国の文字 - > < 依存> < groupIdを> com.belerweb </ groupIdを> < たartifactId > pinyin4j </ たartifactId > < バージョン> 2.5.0 </ バージョン> </ 依存関係>