spring boot: 用pinyin4j把中文转换为汉语拼音(spring boot v2.5.4)


一,关于pinyin4j:

代码地址:
https://github.com/belerweb/pinyin4j
在mvn的地址
https://mvnrepository.com/artifact/com.belerweb/pinyin4j/2.5.1

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

         对应的源码可以访问这里获取: https://github.com/liuhongdi/
         或: https://gitee.com/liuhongdi

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,引入第三方库

pom.xml

        
        <dependency>
            <groupId>com.belerwebgroupId>
            <artifactId>pinyin4jartifactId>
            <version>2.5.1version>
        dependency>

三,java代码

1,封装util类

PinyinUtil.java

package com.yj.storeback.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class PinyinUtil {
    public static void main(String[] args) {
    }

    /**
     * @param chinaStr 中文字符串
     * @return 中文字符串转拼音 其它字符不变
     */
    public static String getPinyin(String chinaStr){
        HanyuPinyinOutputFormat formart = new HanyuPinyinOutputFormat();
        formart.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        formart.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        formart.setVCharType(HanyuPinyinVCharType.WITH_V);
        char[] arrays = chinaStr.trim().toCharArray();
        String result = "";
        try {
            for (int i=0;i) {
                char ti = arrays[i];
                if(Character.toString(ti).matches("[\\u4e00-\\u9fa5]")){ //匹配是否是中文
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(ti,formart);
                    result += temp[0];
                }else{
                    result += ti;
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }

        //判断如果包含重庆,则替换拼音中的zhongqing为chongqing
        if (chinaStr.indexOf("重庆") == -1) {
            //do nothing
        }  else {
            result = result.replace("zhongqing","chongqing");
        }

        return result;
    }
}

2,调用:

        upMap.put("enCity",PinyinUtil.getPinyin(city));
        upMap.put("enAddress",PinyinUtil.getPinyin(address));

四,测试效果

五,查看spring boot的版本:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.5.4)