pinyin4j拼接用户姓名拼音和首字字符

需求:

将用户名称转换成"拼音+首字母"  例如:孙悟空  转成“sunwukong^swk”

pinyin4j拼接用户姓名拼音和首字字符_第1张图片

 核心代码:

package com.jjwc.workflow.utils;

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.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class PinyinUtills {

    public static void main(String[] args) {
        String str= PinyinUtills.pinYinOf("孙悟空");
        System.out.println(str);
    }
    //遍历名字拼音
    public static String pinYinOf(String hanziString) {
        StringBuilder stringBuilder = new StringBuilder();
        String tempString=null;
        String c ="" ;
        if (null != hanziString) {
            for (int i = 0; i < hanziString.length(); i++) {
                tempString = getPinYinOfChar(hanziString.charAt(i));
                c += String.valueOf(tempString.charAt(0));
                stringBuilder.append(tempString);
            }
        }
        return stringBuilder.toString()+"^"+c;
    }
    //遍历首字母
    private static String getPinYinOfChar(char hanziChar) {
        String[] stringArray = null;
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setVCharType(HanyuPinyinVCharType.WITH_V);
        StringBuilder builder = new StringBuilder();
        try {
            stringArray = PinyinHelper.toHanyuPinyinStringArray(hanziChar, format);
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }
        if (null != stringArray) {    //判断姓名后,遍历拼音
            return stringArray[0];
        } else {
            return "";
        }
    }


}

结果:

pinyin4j拼接用户姓名拼音和首字字符_第2张图片

 

你可能感兴趣的:(java,算法,开发语言)