导包
<!-- https://mvnrepository.com/artifact/com.belerweb/pinyin4j -->
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.1</version>
</dependency>
代码
/**
* 全拼(小写)
*/
@Test
public void testOne() {
String str = "太上老君,急急如律令";
char a[] = null;
a = str.toCharArray();
String[] b = new String[a.length];
HanyuPinyinOutputFormat c = new HanyuPinyinOutputFormat();
c.setCaseType(HanyuPinyinCaseType.LOWERCASE);
c.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
c.setVCharType(HanyuPinyinVCharType.WITH_V);
String d = "";
int e = a.length;
try {
for (int i = 0; i < e; i++) {
if (Character.toString(a[i]).matches("[\\u4E00-\\u9FA5]+")) {
b = PinyinHelper.toHanyuPinyinStringArray(a[i], c);
d += b[0];
} else {
d += Character.toString(a[i]);
}
}
System.out.println(d.toUpperCase());
} catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
badHanyuPinyinOutputFormatCombination.printStackTrace();
}
System.out.println(d+"====");
}
/**
* 拼音首字母(大写)
*/
@Test
public void testTwo() {
String str = "太上老君,急急如律令";
String f = "";
for (int i = 0; i < str.length(); i++) {
char g = str.charAt(i);
String[] arr = PinyinHelper.toHanyuPinyinStringArray(g);
if (arr != null) {
f += arr[0].charAt(0);
} else {
f += g;
}
}
System.out.println(f.toUpperCase());
}