使用Hutool工具类 官网链接
以下为Hutool支持的拼音库的pom坐标,你可以选择任意一个引入项目中,如果引入多个,Hutool会按照以上顺序选择第一个使用。
<dependency><groupId>io.github.biezhi</groupId><artifactId>TinyPinyin</artifactId><version>2.0.3.RELEASE</version></dependency><dependency><groupId>com.belerweb</groupId><artifactId>pinyin4j</artifactId><version>2.5.1</version></dependency><dependency><groupId>com.github.stuxuhai</groupId><artifactId>jpinyin</artifactId><version>1.1.8</version></dependency>
使用链接
查看Hutool最新版本
<!--词库--><dependency><groupId>io.github.biezhi</groupId><artifactId>TinyPinyin</artifactId><version>2.0.3.RELEASE</version></dependency><!--Hutool工具类--><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.4</version></dependency>
import cn.hutool.extra.pinyin.PinyinUtil;public class Test {public static void main(String[] args) {// 获取全部汉字首字母,第二个参数为分隔符String str1 = PinyinUtil.getFirstLetter("测试","-"); //c-s// 返回全部拼音 默认分隔符为空格,可以添加第二个参数分隔符String str2 = PinyinUtil.getPinyin("测试"); // ce shiString str3 = PinyinUtil.getPinyin("测试","-");// ce-shi}}
判断字符串是否为中文
//判断是否为中文private static Boolean isChinese(String str) {if (str.trim().matches("[\u4E00-\u9FA5]+")) {return true;} else return false;}