Java漢字変換ピンインpinyin 4 j
3179 ワード
package com.joyce.pinyin4j;
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;
/**
* PinYin4j
* @author Joyce.Luo
* @date 2015-5-14 01:04:38
* @version V3.0
* @since Tomcat6.0,Jdk1.6
* @copyright Copyright (c) 2015
*/
public class PinyinUtil {
public static void main(String[] args) {
String str1 = PinyinUtil.toPinyinString(' ');
System.out.println("chinese char --> " + str1);
String str2 = PinyinUtil.toPinyinString('c');
System.out.println("english char --> " + str2);
String str3 = PinyinUtil.toPinyinString(" ");
System.out.println("chinese string --> " + str3);
String str4 = PinyinUtil.toPinyinString("Hello World");
System.out.println("english string --> " + str4);
String str5 = PinyinUtil.toPinyinString("Hi ,hello world!");
System.out.println("chinese and english --> " + str5);
}
/**
* Pinyin
* @return Pinyin
* @author Joyce.Luo
* @date 2015-5-14 01:40:10
* @version V3.0
* @since Tomcat6.0,Jdk1.6
* @copyright Copyright (c) 2015
*/
private static HanyuPinyinOutputFormat getPinyinFormat(){
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
/*
* UPPERCASE: (ZHONG)
* LOWERCASE: (zhong)
*/
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
/*
* WITHOUT_TONE: (zhong)
* WITH_TONE_NUMBER:1-4 (zhong4)
* WITH_TONE_MARK: ( WITH_U_UNICODE ) (zhòng)
*/
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
/*
* WITH_V: v ü (nv)
* WITH_U_AND_COLON: "u:" ü (nu:)
* WITH_U_UNICODE: ü (nü)
*/
format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
//
return format;
}
/**
* Pinyin
* ,
* ,
* @param c
* @return
* @author Joyce.Luo
* @date 2015-5-14 01:34:55
* @version V3.0
* @since Tomcat6.0,Jdk1.6
* @copyright Copyright (c) 2015
*/
public static String toPinyinString(char c) {
HanyuPinyinOutputFormat format = PinyinUtil.getPinyinFormat();
try {
String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(c, format);
if (null == pinyin || pinyin.length < 1) {
return String.valueOf(c);
}
return pinyin[0];
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Pinyin
* @param str
* @return
* @author Joyce.Luo
* @date 2015-5-14 01:38:17
* @version V3.0
* @since Tomcat6.0,Jdk1.6
* @copyright Copyright (c) 2015
*/
public static String toPinyinString(String str){
if (null == str || "".equals(str)) {
return null;
}
StringBuilder sb = new StringBuilder();
String tempPinyin = null;
for (int i = 0; i < str.length(); i++) {
tempPinyin = PinyinUtil.toPinyinString(str.charAt(i));
sb.append(tempPinyin);
}
return sb.toString();
}
}