为了看起来更直观就没有将这些例子写入事务逻辑层而是写进了controller中
导入依赖
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.1</version>
</dependency>
1、生成拼音简码(大写)
@GetMapping("/dxpj")
public static void dp(String chines) {
String pinyinName = "";
char[] nameChar = chines.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < nameChar.length; i++) {
if (nameChar[i] > 128) {
try {
pinyinName += PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[0].charAt(0);
}catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
pinyinName += nameChar[i];
}
}
System.out.println(pinyinName);
}
2、生成拼音简码(小写)
@GetMapping("/pj")
public static void pyjm(String str) {
String context = "";
for (int j = 0; j < str.length(); j++) {
char word = str.charAt(j);
String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
if (pinyinArray != null) {
context += pinyinArray[0].charAt(0);
} else {
context += word;
}
}
System.out.println(context);
}
3、生成拼音全码(大写 UPPERCASE )
@GetMapping("/qp")
public static void qp(String ch) throws BadHanyuPinyinOutputFormatCombination {
//1.new一个汉语拼音输出格式对象
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
//2.设置格式
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); //1).设置声调标识为空
format.setCaseType(HanyuPinyinCaseType.UPPERCASE); //2).设置大小写转换为大写
format.setVCharType(HanyuPinyinVCharType.WITH_U_AND_COLON); //3).设置ü的格式为u,如为默认则本条语句也可不写
//3.待处理的字符串
char[] chs = ch.toCharArray(); //转换成字符数组
String hanYuPinyinString =
PinyinHelper.toHanYuPinyinString(
ch, //1).参数一:带处理字符串
format, //2).参数二:编码格式
" ", //3).参数三:每个拼音分隔符(这里设置为空格)
true); //4).参数四:是否保留不能转换成拼音字符的字符
//4.打印结果
System.out.println(hanYuPinyinString);
}
4、生成拼音全码(小写 LOWERCASE)
@GetMapping("/qp")
public static void qp(String ch) throws BadHanyuPinyinOutputFormatCombination {
//1.new一个汉语拼音输出格式对象
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
//2.设置格式
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); //1).设置声调标识为空
format.setCaseType(HanyuPinyinCaseType.LOWERCASE); //2).设置大小写转换为小写
format.setVCharType(HanyuPinyinVCharType.WITH_U_AND_COLON); //3).设置ü的格式为u,如为默认则本条语句也可不写
//3.待处理的字符串
char[] chs = ch.toCharArray(); //转换成字符数组
String hanYuPinyinString =
PinyinHelper.toHanYuPinyinString(
ch, //1).参数一:带处理字符串
format, //2).参数二:编码格式
" ", //3).参数三:每个拼音分隔符(这里设置为空格)
true); //4).参数四:是否保留不能转换成拼音字符的字符
//4.打印结果
System.out.println(hanYuPinyinString);
}