中文字符串转拼音

一、前言

在对字符串进行字母排序的时候(例如通讯录列表),就会涉及到汉字转拼音。

二、转换方法

1.使用第三方jar包:pinyin4j-2.5.0.jar
2.转换具体实现类:

public class PinyinUtil {

    /**
     * 将传进来的包含中文的字串转成拼音
     * 
     * @param str
     * @return pinyin
     */
    public static String getPinyin(String str) {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 去掉读音
        format.setCaseType(HanyuPinyinCaseType.UPPERCASE); // 输出大写字母

        char[] charArray = string.toCharArray();

        StringBuilder sb = new StringBuilder();

        // 遍历字母串中的每一个字符
        for (int i = 0; i < charArray.length; i++) {
            char c = charArray[i]; // 指定位置字符

            // 去掉空格,
            if (Character.isWhitespace(c)) {
                continue; // 跳过循环
            }
            if (isChinese(c)) {
                // 可能是汉字
                try {
                    // 转成拼音
                    String s = PinyinHelper.toHanyuPinyinStringArray(c, format)[0];
                    sb.append(s); // 拼接
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {// 不是汉字, 直接拼接
                sb.append(c);
            }
        }
        return sb.toString();
    }

    //判断当前字符是否是中文字符
    private static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                ||ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS ) {
            return true;
        }
        return false;
    }

}

猜你喜欢

转载自blog.csdn.net/wangwasdf/article/details/74942196
今日推荐