1 package com.red.test;
2
3 import net.sourceforge.pinyin4j.PinyinHelper;
4 import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
5 import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
6 import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
7 import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
8
9 /**
10 * 汉字转换为拼音
11 * @author Red
12 */
13 public class PinyinDemo {
14 /**
15 * 测试main方法
16 * @param args
17 */
18 public static void main(String[] args) {
19 System.out.println(ToFirstChar("汉字转换为拼音").toUpperCase()); //转为首字母大写
20 System.out.println(ToPinyin("汉字转换为拼音"));
21 }
22 /**
23 * 获取字符串拼音的第一个字母
24 * @param chinese
25 * @return
26 */
27 public static String ToFirstChar(String chinese){
28 String pinyinStr = "";
29 char[] newChar = chinese.toCharArray(); //转为单个字符
30 HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
31 defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
32 defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
33 for (int i = 0; i < newChar.length; i++) {
34 if (newChar[i] > 128) {
35 try {
36 pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0].charAt(0);
37 } catch (BadHanyuPinyinOutputFormatCombination e) {
38 e.printStackTrace();
39 }
40 }else{
41 pinyinStr += newChar[i];
42 }
43 }
44 return pinyinStr;
45 }
46
47 /**
48 * 汉字转为拼音
49 * @param chinese
50 * @return
51 */
52 public static String ToPinyin(String chinese){
53 String pinyinStr = "";
54 char[] newChar = chinese.toCharArray();
55 HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
56 defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
57 defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
58 for (int i = 0; i < newChar.length; i++) {
59 if (newChar[i] > 128) {
60 try {
61 pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0];
62 } catch (BadHanyuPinyinOutputFormatCombination e) {
63 e.printStackTrace();
64 }
65 }else{
66 pinyinStr += newChar[i];
67 }
68 }
69 return pinyinStr;
70 }
71 }
|