中文转拼音

github

  • HanYuToString 工具类

    1. public class HanYuToString {
    2. private final static HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
    3. /**
    4. * 汉字转字符串(使用format)
    5. * @param chinese
    6. * @return
    7. * @throws BadHanyuPinyinOutputFormatCombination
    8. */
    9. public static String toString(String chinese) throws BadHanyuPinyinOutputFormatCombination {
    10. StringBuilder stringBuilder = new StringBuilder();
    11. for (char ch : chinese.toCharArray()) {
    12. String[] strings = PinyinHelper.toHanyuPinyinStringArray(ch,format);
    13. System.out.println(Arrays.toString(strings));
    14. stringBuilder.append(strings[0]);
    15. }
    16. return stringBuilder.toString();
    17. }
    18. /**
    19. * 不带音调标记 eg 中国 zhongguo
    20. * @param chinese
    21. * @return
    22. * @throws BadHanyuPinyinOutputFormatCombination
    23. */
    24. public static String toStringWithOutTone(String chinese) throws BadHanyuPinyinOutputFormatCombination {
    25. format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
    26. return toString(chinese);
    27. }
    28. /**
    29. * 带音调 eg 中国 zhong1guo2
    30. * @param chinese
    31. * @return
    32. */
    33. public static String toStringWithTone(String chinese) throws BadHanyuPinyinOutputFormatCombination {
    34. format.setToneType(HanyuPinyinToneType.WITH_TONE_NUMBER);
    35. return toString(chinese);
    36. }
    37. }