PinyinUtil.java
1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.xly.util;
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.exception.BadHanyuPinyinOutputFormatCombination;
public class PinyinUtil {
private static final HanyuPinyinOutputFormat FORMAT = new HanyuPinyinOutputFormat();
static {
FORMAT.setCaseType(HanyuPinyinCaseType.LOWERCASE); // 小写
FORMAT.setToneType(HanyuPinyinToneType.WITHOUT_TONE); // 不带声调
}
public static String convertToPinyin(Object input) {
if (input == null) {
return "";
}
String sVal = input.toString().trim();
if (sVal.isEmpty()) {
return "";
}
try {
StringBuilder result = new StringBuilder();
char[] chars = sVal.toCharArray();
for (char ch : chars) {
// 判断是否为汉字
if (String.valueOf(ch).matches("[\\u4E00-\\u9FA5]+")) {
String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(ch, FORMAT);
if (pinyinArray != null && pinyinArray.length > 0) {
// 多音字取第一个
result.append(pinyinArray[0]);
} else {
result.append(ch); // 无法转换保留原字符
}
} else {
result.append(ch); // 非汉字直接保留
}
}
return result.toString() + "_";
} catch (BadHanyuPinyinOutputFormatCombination e) {
System.err.println("拼音转换异常: " + sVal + ", " + e.getMessage());
return sVal + "_";
}
}
}