簡介
在我們使用手機通訊錄或各種APP的搜索功能時,既可以根據中文搜索,也可以根據拼音搜索,這種時候就使用到了中文轉拼音的功能了。
實現
pinyin4j
引入maven依賴
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.1</version>
</dependency>
實例
public class Client {
public static void main(String[] args) throws BadHanyuPinyinOutputFormatCombination {
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
//拼音小寫
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
//不帶聲調
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
//要轉換的中文,格式,轉換之后的拼音的分隔符,遇到不能轉換的是否保留 wo,shi,zhong,guo,ren,,hello
System.out.println(PinyinHelper.toHanYuPinyinString("我是中國人,hello", format, ",", true));
}
}
輸出結果為
wo,shi,zhong,guo,ren,,hello
可以看到使用開源工具包實現中文轉拼音還是很簡單的。
其實就是將所有中文和對應的拼音保存起來並加載到內存中,轉換時直接查找。
jpinyin
引入maven依賴
<dependency>
<groupId>com.github.stuxuhai</groupId>
<artifactId>jpinyin</artifactId>
<version>1.1.8</version>
</dependency>
實例
public class Client {
public static void main(String[] args) throws PinyinException {
//要轉換的中文,轉換之后的拼音分隔符,拼音格式帶聲調 wǒshìzhōngguórén,hello
System.out.println(
PinyinHelper.convertToPinyinString("我是中國人,hello", "", PinyinFormat.WITH_TONE_MARK));
}
}
原理也是提前保存轉換關系直接查詢。