中文转拼音

2020-12-28

java

时间最不偏私,给任何人都是二十四小时;时间也最偏私,给任何人都不是二十四小时。──赫胥黎

引入依赖

1
2
3
4
5
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>

编写代码

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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.ruben.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.exception.BadHanyuPinyinOutputFormatCombination;

import java.util.Random;

/**
* 提取汉字首字母工具类
*/
public class ChineseToFirstLetterUtil {
/**
* 汉字转拼音大写首字母
*
* @param c
* @return
*/
public static String ChineseToFirstLetter(String c) {
StringBuilder string = new StringBuilder();
char b;
int a = c.length();
for (int k = 0; k < a; k++) {
b = c.charAt(k);
String d = String.valueOf(b);
String str = converterToFirstSpell(d);
String s = str.toUpperCase();
String g = s;
char h;
for (int y = 0; y <= 0; y++) {
h = g.charAt(0);
string.append(h);
}
}
return string.toString();
}

/**
* 汉子转拼音
*
* @param chines
* @return
*/
public static String converterToFirstSpell(String chines) {
StringBuilder pinyinName = new StringBuilder();
char[] nameChar = chines.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < nameChar.length; i++) {
String s = String.valueOf(nameChar[i]);
if (s.matches("[\\u4e00-\\u9fa5]")) {
try {
String[] mPinyinArray = PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat);
pinyinName.append(mPinyinArray[0]);
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
pinyinName.append(nameChar[i]);
}
}
return pinyinName.toString();
}

public static void main(String[] args) {
System.out.println(ChineseToFirstLetter("干饭人干饭魂干饭都是人上人"));
System.out.println(converterToFirstSpell("今日干饭不狠,明日地位不稳"));
}
}

执行结果
image-20201228193248891