在我们使用手机通讯录或各种APP的搜索功能时,既可以根据中文搜索,也可以根据拼音搜索,这种时候就使用到了中文转拼音的功能了。
实现pinyin4j
引入maven依赖
com.belerweb pinyin4j2.5.1
实例
public class Test{
public static void main(String[] args) throws BadHanyuPinyinOutputFormatCombination {
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
//拼音小写
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
//不带声调
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
//要转换的中文,格式,转换之后的拼音的分隔符,遇到不能转换的是否保留 wo,shi,zhong,wen
System.out.println(PinyinHelper.toHanYuPinyinString("我是中文", format, ",", true));
}
}
输出结果为
wo,shi,zhong,wen



