取汉字拼音首字母--生成不重复ID(汉字--拼音--首字母)

时间:2022-05-27 08:04:40

工作上需要生成一些不重复的Id,并且Id是固定前缀加客户拼音首字母相连产生的,如有重复,末尾加数字

首先是汉字转拼音的jar包


public String getUniqueAk(String cust_name){
		int index=0;
		String value = "";
		while(true){			
			StringBuffer sb = new StringBuffer("a.c.l.");
			sb.append(cn2FirstSpell(cust_name));
			if(index != 0){
				sb.append(index);
			}
			index++;
			String str = sb.toString();
			A a = aService.get(str);//是否重复
			if(aService.get(str) == null){
				value = str;
				break;//不重复就跳出
			}
		}
		return value;
	}

public String cn2FirstSpell(String chinese) {
        StringBuffer pybf = new StringBuffer();
        char[] arr = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < arr.length; i++) {
                if (arr[i] > 128) {
                        try {
                                String[] _t = PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat);
                                if (_t != null) {
                                        pybf.append(_t[0].charAt(0));
                                }
                        } catch (BadHanyuPinyinOutputFormatCombination e) {
                                e.printStackTrace();
                        }
                } else {
                        pybf.append(arr[i]);
                }
        }
        return pybf.toString().replaceAll("\\W", "").trim();
}