PinYinUtils.java 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package com.yihu.jw.utils;
  2. import net.sourceforge.pinyin4j.PinyinHelper;
  3. import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
  4. import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
  5. import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
  6. import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
  7. /**
  8. * @author huangwenjie
  9. * @date 2020/3/13 09:32
  10. */
  11. public class PinYinUtils {
  12. //将中文转换为英文
  13. public static String getEname(String name) throws Exception
  14. {
  15. HanyuPinyinOutputFormat pyFormat = new HanyuPinyinOutputFormat();
  16. pyFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
  17. pyFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
  18. pyFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
  19. return PinyinHelper.toHanyuPinyinString(name, pyFormat, "");
  20. }
  21. //姓、名的第一个字母需要为大写
  22. public static String getUpEname(String name) throws Exception {
  23. char[] strs = name.toCharArray();
  24. String newname = null;
  25. //名字的长度
  26. if (strs.length == 2) {
  27. newname = toUpCase(getEname("" + strs[0])) + " "
  28. + toUpCase(getEname("" + strs[1]));
  29. } else if (strs.length == 3)
  30. {
  31. newname = toUpCase(getEname("" + strs[0])) + " "
  32. + toUpCase(getEname("" + strs[1] + strs[2]));
  33. }
  34. else if (strs.length == 4)
  35. {
  36. newname = toUpCase(getEname("" + strs[0] + strs[1])) + " "
  37. + toUpCase(getEname("" + strs[2] + strs[3]));
  38. } else
  39. {
  40. newname = toUpCase(getEname(name));
  41. }
  42. return newname;
  43. }
  44. //首字母大写
  45. private static String toUpCase(String str) {
  46. StringBuffer newstr = new StringBuffer();
  47. newstr.append((str.substring(0, 1)).toUpperCase()).append(
  48. str.substring(1, str.length()));
  49. return newstr.toString();
  50. }
  51. public static void main(String[] args) throws Exception{
  52. System.out.println(getUpEname("李宇春"));
  53. }
  54. }