一、引入Maven依赖
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>
二、代码
import com.gyyjy.portal.pojo.cms.sm.SelectTreeVO;
import net.sourceforge.pinyin4j.PinyinHelper;
import java.util.Comparator;
public class Chinese2Pinyin {
private String toPinYinString(String str) {
StringBuilder sb = new StringBuilder();
String[] arr = null;
for (int i = 0; i < str.length(); i++) {
arr = PinyinHelper.toHanyuPinyinStringArray(str.charAt(i));
if (arr != null && arr.length > 0) {
for (String string : arr) {
sb.append(string);
}
} else {
sb.append(str.charAt(i));
}
}
return sb.toString();
}
public static void main(String[] args) {
Chinese2Pinyin chinese = new Chinese2Pinyin();
System.out.println(chinese.toPinYinString("天河人员1"));
System.out.println(chinese.toPinYinString("天河人员2"));
}
}
三、测试
到此这篇关于Java汉字转拼音案例详解的文章就介绍到这了,更多相关Java汉子转拼音内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!