使用pinyin4j
汉字转换拼音在日常开发中是个很常见的需求场景,而pinyin4j就是一个Java获取汉字的拼音的工具库,下载地址:http://sourceforge.net/projects/pinyin4j/
1. maven中使用pinyin4j
- 首先添加maven依赖:
xml
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.1</version>
</dependency>
- 编写代码
java
@Test
public void test1() throws Exception{
HanyuPinyinOutputFormat pinyinOutputFormat = new HanyuPinyinOutputFormat();
// UPPERCASE:大写 (ZHONG)
// LOWERCASE:小写 (zhong)
pinyinOutputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
// WITHOUT_TONE:无音标 (zhong)
// WITH_TONE_NUMBER:1-4数字表示英标 (zhong4)
// WITH_TONE_MARK:直接用音标符(必须WITH_U_UNICODE否则异常) (zhòng)
pinyinOutputFormat.setToneType(HanyuPinyinToneType.WITH_TONE_MARK);
// WITH_V:用v表示ü (nv)
// WITH_U_AND_COLON:用"u:"表示ü (nu:)
// WITH_U_UNICODE:直接用ü (nü)
pinyinOutputFormat.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
String[] pinyins = PinyinHelper.toHanyuPinyinStringArray('刘', pinyinOutputFormat);
System.out.println(Arrays.toString(pinyins));
}
运行结果: