Java中文(汉子)转换拼音
生活随笔
收集整理的這篇文章主要介紹了
Java中文(汉子)转换拼音
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
簡介
????????在我們使用各種APP的搜索功能時,既可以根據(jù)中文搜索,也可以根據(jù)拼音搜索。
? ? ? ? 根據(jù)業(yè)務的需求來應對。
實現(xiàn)
????????pinyin4j? -- 引入maven依賴
<dependency><groupId>com.belerweb</groupId><artifactId>pinyin4j</artifactId><version>2.5.1</version> </dependency>Java代碼:
package com.example.thread.projectTest;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;import java.io.UnsupportedEncodingException;public class Pinyin {/*** @param chinese (字符串 漢字)* @return 漢字轉(zhuǎn)拼音 其它字符不變*/public static String getAllSpell(String chinese){StringBuffer buffer = new StringBuffer();HanyuPinyinOutputFormat formart = new HanyuPinyinOutputFormat();formart.setCaseType(HanyuPinyinCaseType.LOWERCASE);formart.setToneType(HanyuPinyinToneType.WITHOUT_TONE);formart.setVCharType(HanyuPinyinVCharType.WITH_V);char[] array = chinese.trim().toCharArray();try {for (int i = 0;i < array.length; i++) {char t = array[i];//匹配是否是中文if(Character.toString(t).matches("[\\u4e00-\\u9fa5]")){ String[] temp = PinyinHelper.toHanyuPinyinStringArray(t,formart);buffer.append(temp[0]);}else{buffer.append(t);}}} catch (BadHanyuPinyinOutputFormatCombination e) {e.printStackTrace();}return buffer.toString().replaceAll("\\W", "").trim();}/*** 獲取漢字串拼音首字母,英文字符不變* @param chinese 漢字串* @return 漢語拼音首字母小寫 大寫可以自動轉(zhuǎn)換*/public static String getFirstSpell(String chinese) {StringBuffer buffer = new StringBuffer();char[] array = chinese.toCharArray();HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);for (int i = 0; i < array.length; i++) {if (array[i] > 128) {try {String[] temp = PinyinHelper.toHanyuPinyinStringArray(array[i], defaultFormat);if (temp != null) {// 截取首字母 小寫buffer.append(temp[0].charAt(0));/* 字母大寫char charAt = temp[0].charAt(0);charAt -= 32; // 改變字符的編碼值buffer.append(charAt);*/}} catch (BadHanyuPinyinOutputFormatCombination e) {e.printStackTrace();}} else {buffer.append(array[i]);}}return buffer.toString().replaceAll("\\W", "").trim();}}測試一下:
?
總結
以上是生活随笔為你收集整理的Java中文(汉子)转换拼音的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 录屏并制作动图gif的方法
- 下一篇: java 汉字乱码_【转】Java中文乱