zoukankan      html  css  js  c++  java
  • 汉语转拼音pinyin4j

    分享一个将汉语转成拼音的工具包:pinyin4j-2.5.0.jar,下载地址:http://download.csdn.net/detail/abc_key/7629141

    使用例如以下代码

    import net.sourceforge.pinyin4j.PinyinHelper;
    
    public class HanyuToPinyin {
    
    	/*
    	 * 讲汉语转成拼音
    	 */
    	public static String ToHanyuPinyin(String sourceStr, boolean isUpperCase) {
    		int sourceLen = sourceStr == null ? 0 : sourceStr.length();
    		if (sourceLen < 1)
    			return "";
    		StringBuffer pinyinStrBuf = new StringBuffer();
    		for (int idx = 0; idx < sourceLen; idx++) {
    			String[] tmpData = PinyinHelper.toHanyuPinyinStringArray(sourceStr
    					.charAt(idx));
    			if (tmpData != null && tmpData.length > 0
    					&& tmpData[0].length() > 0) {
    				if (isUpperCase) {
    					pinyinStrBuf.append(tmpData[0].substring(0,
    							tmpData[0].length() - 1).toUpperCase());
    				} else {
    					pinyinStrBuf.append(tmpData[0].substring(0, tmpData[0]
    							.length() - 1));
    				}
    			}
    		}
    		return pinyinStrBuf.toString();
    	}
    	
    	/*
    	 * 汉语转成拼音的首字母
    	 */
    	public static String ToHanyuPinyinHead(String sourceStr, boolean isUpperCase) {
    		int sourceLen = sourceStr == null ? 0 : sourceStr.length();
    		if (sourceLen < 1)
    			return "";
    		StringBuffer pinyinStrBuf = new StringBuffer();
    		for (int idx = 0; idx < sourceLen; idx++) {
    			String[] tmpData = PinyinHelper.toHanyuPinyinStringArray(sourceStr
    					.charAt(idx));
    			if (tmpData != null && tmpData.length > 0
    					&& tmpData[0].length() > 0) {
    				if (isUpperCase) {
    					pinyinStrBuf.append(tmpData[0].substring(0,
    							1).toUpperCase());
    				} else {
    					pinyinStrBuf.append(tmpData[0].substring(0, 1));
    				}
    			}
    			//物品名称中不能转换成拼音的部分(英数)会原样保存
    			else{
    				pinyinStrBuf.append(sourceStr.charAt(idx));
    			}
    		}
    		return pinyinStrBuf.toString();
    	}
    }
    


  • 相关阅读:
    数据结构与算法 ||设计模式
    前端页面知识点
    easyui的dialog中的输入框在关闭后如何清空输入框中的内容
    设计模式之单例模式(通俗易懂,超详细)
    分布式锁--Java1234
    spring cloud Alibaba
    easyui
    SQL查询最大或最新的一条数据
    java中的异常(exception、throw、throws、try···catch)
    git error: The following untracked working tree files would be overwritten by merge:
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/5349175.html
Copyright © 2011-2022 走看看