通讯录获取首字母并以首字母归类返回
效果1 - 返回首字母
效果2 - 返回拼音
代码
package com.dt.wx.miniprogram.app.util;
import lombok.extern.slf4j.Slf4j;
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;
@Slf4j
public class PinyinUtil {
public String convertToPinyin(String chineseLanguage){
char[] cl_chars = chineseLanguage.trim().toCharArray();
String pinyin = "";
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V) ;
try {
for (int i=0; i<cl_chars.length; i++){
if (String.valueOf(cl_chars[i]).matches("[\u4e00-\u9fa5]+")){
pinyin += PinyinHelper.toHanyuPinyinStringArray(cl_chars[i], defaultFormat)[0];
} else {
pinyin += cl_chars[i];
}
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
log.info("字符: {}, 转拼音异常,原因为 {}", chineseLanguage, e);
}
return pinyin;
}
public static String getFirstLetter(String chineseLanguage){
char[] cl_chars = chineseLanguage.trim().toCharArray();
String pinyin = "";
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
try {
String str = String.valueOf(cl_chars[0]);
if (str.matches("[\u4e00-\u9fa5]+")) {
pinyin = PinyinHelper.toHanyuPinyinStringArray(cl_chars[0], defaultFormat)[0].substring(0, 1);
} else if (str.matches("[0-9]+")) {
return "#";
} else if (str.matches("[a-zA-Z]+")) {
pinyin += cl_chars[0];
} else {
return "#";
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
log.info("字符:{},转拼音异常,原因为{}",chineseLanguage,e);
}
return pinyin;
}
}
依赖
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>