漢字轉漢語拼音

hooroom發表於2020-12-03

1 . pom 如下

<dependency>
   <groupId>com.belerweb</groupId>
   <artifactId>pinyin4j</artifactId>
   <version>2.5.0</version>
</dependency>

2.工具類

/**
 * 漢字轉漢語拼音
 *
 */

public static String toHanYuPinYin(String str){

    StringBuffer re = new StringBuffer();

    try {

        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);


        char[] chars = str.toCharArray();

        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if(c=='區'){
                re.append("ou");
            }else {
                String[] strings = PinyinHelper.toHanyuPinyinStringArray(chars[i], format);
                re.append(strings[0]);
            }

        }

    } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
        badHanyuPinyinOutputFormatCombination.printStackTrace();
    }
    return  re.toString();

}

相關文章