漢字獲取首字符


解決場景

  在某些項目需求中我們需要獲取姓名或者名稱的首字母或者全拼,以用於模糊查詢或者字母查詢,下面的例子就可以很好的解決這個問題,減少大家的工作量

所需jar包

<dependency>
  <groupId>com.belerweb</groupId>
  <artifactId>pinyin4j</artifactId>
  <version>2.5.0</version>
</dependency>
 
        
代碼
package com.ccytsoft.wkc.util;

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

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* 獲取首字母工具
*
* @author kuangxiang
* @Date 15:06 2017/11/24
*/
public class ChineseCharacterUtil {

/**
* 獲取漢字首字母或全拼大寫字母
*
* @param chinese 漢字
* @param isFull 是否全拼 true:表示全拼 false表示:首字母
*
* @return 全拼或者首字母大寫字符竄
*/
public static String getUpperCase(String chinese,boolean isFull){
return convertHanzi2Pinyin(chinese,isFull).toUpperCase();
}

/**
* 獲取漢字首字母或全拼小寫字母
*
* @param chinese 漢字
* @param isFull 是否全拼 true:表示全拼 false表示:首字母
*
* @return 全拼或者首字母小寫字符竄
*/
public static String getLowerCase(String chinese,boolean isFull){
return convertHanzi2Pinyin(chinese,isFull).toLowerCase();
}

/**
* 將漢字轉成拼音
* <P>
* 取首字母或全拼
*
* @param hanzi 漢字字符串
* @param isFull 是否全拼 true:表示全拼 false表示:首字母
*
* @return 拼音
*/
private static String convertHanzi2Pinyin(String hanzi,boolean isFull){
/***
* ^[\u2E80-\u9FFF]+$ 匹配所有東亞區的語言
* ^[\u4E00-\u9FFF]+$ 匹配簡體和繁體
* ^[\u4E00-\u9FA5]+$ 匹配簡體
*/
String regExp="^[\u4E00-\u9FFF]+$";
StringBuffer sb=new StringBuffer();
if(hanzi==null||"".equals(hanzi.trim())){
return "";
}
String pinyin="";
for(int i=0;i<hanzi.length();i++){
char unit=hanzi.charAt(i);
//是漢字,則轉拼音
if(match(String.valueOf(unit),regExp)){
pinyin=convertSingleHanzi2Pinyin(unit);
if(isFull){
sb.append(pinyin);
}
else{
sb.append(pinyin.charAt(0));
}
}else{
sb.append(unit);
}
}
return sb.toString();
}

/**
* 將單個漢字轉成拼音
*
* @param hanzi 漢字字符
*
* @return 拼音
*/
private static String convertSingleHanzi2Pinyin(char hanzi){
HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
String[] res;
StringBuffer sb=new StringBuffer();
try {
res = PinyinHelper.toHanyuPinyinStringArray(hanzi,outputFormat);
sb.append(res[0]);//對於多音字,只用第一個拼音
} catch (Exception e) {
e.printStackTrace();
return "";
}
return sb.toString();
}

/***
* 匹配
* <P>
* 根據字符和正則表達式進行匹配
*
* @param str 源字符串
* @param regex 正則表達式
*
* @return true:匹配成功 false:匹配失敗
*/
private static boolean match(String str,String regex){
Pattern pattern=Pattern.compile(regex);
Matcher matcher=pattern.matcher(str);
return matcher.find();
}

/**
* 測試方法
*/
public static void main(String[] args) {
System.out.println(convertHanzi2Pinyin("阿斯頓發生的發生",false).toUpperCase());
}
}
 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM