中文转拼音-JAVA

2021/10/7 20:43:10

本文主要是介绍中文转拼音-JAVA,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

POM依赖:

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

代码:

HanyuPinyinCaseType.UPPERCASE

private String getFirstLetters(String ChineseLanguage, HanyuPinyinCaseType caseType) {
        char[] cl_chars = ChineseLanguage.trim().toCharArray();
        String hanyupinyin = "";
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(caseType);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        try {
            for(int i = 0; i < cl_chars.length; ++i) {
                String str = String.valueOf(cl_chars[i]);
                if (str.matches("[一-龥]+")) {
                    hanyupinyin = hanyupinyin + PinyinHelper.toHanyuPinyinStringArray(cl_chars[i], defaultFormat)[0].substring(0, 1);
                } else if (str.matches("[0-9]+")) {
                    hanyupinyin = hanyupinyin + cl_chars[i];
                } else if (str.matches("[a-zA-Z]+")) {
                    hanyupinyin = hanyupinyin + cl_chars[i];
                } else {
                    hanyupinyin = hanyupinyin + cl_chars[i];
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination var7) {
            System.out.println("字符不能转成汉语拼音");
        }

        return hanyupinyin;
    }

单字符一个一个转换



这篇关于中文转拼音-JAVA的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程