Home > Java > javaTutorial > Java code that completes the conversion function between Chinese and Pinyin

Java code that completes the conversion function between Chinese and Pinyin

黄舟
Release: 2017-05-15 09:57:04
Original
1612 people have browsed it

这篇文章主要介绍了java实现将汉语转换为拼音功能,非常不错,具有参考借鉴价值 ,需要的朋友可以参考下

这几天在做项目的时候用到了通过拼音去数据库表里面去模糊查询汉语字段,刚开始的时候感觉特别神奇,查了好多资料,直接去模糊查询是能实现的,但是貌似很复杂。所以最终取了一个比较容易的方案,就是给数据库表里面新加了一个拼音字段。完美的解决了这个问题,虽说可以这么干,但是数据这么多,全部转换为拼音(人一个一个区输入,有点不现实)。于是就在网上找呀找,就找到了一段直接将汉语转换为拼音的一段代码,在这和大家分享一下。

所需jar:pinyin4j-2.5.0.jar

public static void main(String[] args) {
    System.out.println(getPingYin("小龙驿站"));
  }
  public static String getPingYin(String str) {
    char[] t1 = null;
    t1 = str.toCharArray();
    String[] t2 = new String[t1.length];
    HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
    t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
    t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
    t3.setVCharType(HanyuPinyinVCharType.WITH_V);
    String t4 = "";
    int t0 = t1.length;
    try {
      for (int i = 0; i < t0; i++) {
        // 判断能否为汉字?
        if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {
          t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);// 将汉字的几种全拼都存到t2数组?
          t4 += t2[0];// 取出该汉字全拼的第一种读音并连接到字符串t4?
        } else {
          // 如果不是汉字字符,间接取出字符并连接到字符串t4?
          t4 += Character.toString(t1[i]);
        }
      }
    } catch (BadHanyuPinyinOutputFormatCombination e) {
      e.printStackTrace();
    }
    return t4;
Copy after login

【相关推荐】

1. 特别推荐“php程序员工具箱”V0.1版本下载

2. Java免费视频教程

3. YMP在线手册

The above is the detailed content of Java code that completes the conversion function between Chinese and Pinyin. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template