前提是導包hanyu4j
pom.xml引入
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>
@Test
public void test() throws BadHanyuPinyinOutputFormatCombination {
//定義一個字符串
String s = "這是測試字符串";
//轉成字符數(shù)組
char[] chars = s.toCharArray();
//導入pinyin4j,并設置屬性
HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
t3.setVCharType(HanyuPinyinVCharType.WITH_V);
for(Integer i =0;i<chars.length;i++){
//將字符轉為拼音,需要用一個數(shù)組接收
String[] strings = PinyinHelper.toHanyuPinyinStringArray(chars[i], t3);
System.out.println(strings[0]);
}
}
控制臺輸出的是
Paste_Image.png
不用謝!