java获取汉子的拼音

来源:互联网 发布:java数组实现二叉树 编辑:程序博客网 时间:2024/04/28 02:21

今天任务需要,查了许多资料终于找到一个可以获取汉子的拼音的jar吧,官网http://pinyin4j.sourceforge.net我登不上

引用pinyin4j.jar

import java.io.IOException;import java.util.regex.Matcher;import java.util.regex.Pattern;import net.sourceforge.pinyin4j.PinyinHelper;import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;public class PinYinHelper {private static HanyuPinyinOutputFormat spellFormat = new HanyuPinyinOutputFormat();// 判断字符串是否包含有中文   public static boolean isChinese(String str) {String regex = "[\\u4e00-\\u9fa5]";Pattern pattern = Pattern.compile(regex);Matcher matcher = pattern.matcher(str);return matcher.find();}public static String chineneToPinyin(String chineseStr) {spellFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);spellFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);spellFormat.setVCharType(HanyuPinyinVCharType.WITH_V);String pinYin = "";if(isChinese(chineseStr)){pinYin = PinyinHelper.toHanyuPinyinString(chineseStr, spellFormat, "").toUpperCase();}else{pinYin = chineseStr.toUpperCase();}return pinYin;}public static void main(String[] args){System.out.println(chineneToPinyin("我爱中国"));}}