中文转拼音

package com.tao.acl.common.util;

import org.apache.commons.lang3.ObjectUtils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;

public class ChineseSpellingUtil {

	  public static void main(String[] args)
	  {
	    String simpleString = "测试用例";
	    String complexString = "中国红红sdfsd#%66^$@5";
	    System.out.println(simpleString + " = " + 
	      getFullSpelling(simpleString));
	    System.out.println(complexString + " = " + 
	      getFullSpelling(complexString));
	    
	    System.out.println(simpleString + " = " + 
	      getFirstSpelling(simpleString));
	    System.out.println(complexString + " = " + 
	      getFirstSpelling(complexString));
	    
	  }
	  
	  private static String toPinyin(char ch)
	  {
	    HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
	    outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
	    outputFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
	    String[] pinyinArray = null;
	    try
	    {
	      pinyinArray = PinyinHelper.toHanyuPinyinStringArray(ch, 
	        outputFormat);
	    }
	    catch (Exception e1)
	    {
	      e1.printStackTrace();
	    }
	    if ((pinyinArray != null) && (pinyinArray.length > 0))
	    {
	      StringBuffer pinyinStrBuf = new StringBuffer();
	      pinyinStrBuf.append(pinyinArray[0]);
	      
	      return pinyinStrBuf.toString();
	    }
	    return null;
	  }
	  
	  private static String getSpelling(String source, boolean firstLetter)
	  {
	    if (ObjectUtils.isEmpty(source)) {
	      return source;
	    }
	    StringBuffer buffer = new StringBuffer();
	    for (int i = 0; i < source.length(); i++)
	    {
	      char ch = source.charAt(i);
	      if ((ch < '?') && (ch > 0))
	      {
	        buffer.append(ch);
	      }
	      else
	      {
	        String pinyin = toPinyin(ch);
	        if (pinyin != null) {
	          buffer.append(firstLetter ? pinyin.substring(0, 1) : 
	            pinyin);
	        } else {
	          buffer.append(ch);
	        }
	      }
	    }
	    return buffer.toString();
	  }
	  
	  public static String getFullSpelling(String source)
	  {
	    return getSpelling(source, false);
	  }
	  
	  public static String getFirstSpelling(String source)
	  {
	    return getSpelling(source, true);
	  }
}

上述代码执行之后输出

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-30zh3yNm-1624717474903)(C:\Users\sunjiatao\AppData\Roaming\Typora\typora-user-images\image-20210626222220218.png)]

即getFullSpelling()会把中文转成拼音,其他字符保留。而getFirstSpelling()会把中文拼音首字母取出,其他字符保留!




知是行之始,行是知之获!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值