中文转拼音不带声调
引入依赖:
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.1</version>
</dependency>
示例:
public static void main(String[] args) throws Exception{
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
//拼音小写
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
//不带声调
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
/**
* 第一个参数:要转换的中文
* 第二个参数:转换的格式
* 第三个参数:转换之后的拼音的分隔符
* 第四个参数:遇到不能转换的是否保留
* 转换后:hello,shi,jie
*/
System.out.println(PinyinHelper.toHanYuPinyinString("hello,世界", format, ",", true));
}
中文转拼音带声调
引入依赖:
<dependency>
<groupId>com.github.stuxuhai</groupId>
<artifactId>jpinyin</artifactId>
<version>1.1.8</version>
</dependency>
示例:
public static void main(String[] args) throws Exception {
/**
* 第一个参数:要转换的字符串
* 第二个参数:转换之后的拼音分隔符
* 第三个参数:指定拼音格式带声调
* 输出结果:hello,shìjiè
*/
String s = PinyinHelper.convertToPinyinString("hello,世界", "", PinyinFormat.WITH_TONE_MARK);
System.out.println(s);
}