JAVA 生成同音字的方法,隨機生成漢字,漢字轉拼音,寫的不好,望指正.謝謝~
import java.io.UnsupportedEncodingException;
import java.util.Random;
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;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
public class test2 {
public static void main(String[] args) {
String s = "哈嘍";
char[] c = s.toCharArray();
for (int i = 0; i < c.length; i++) {
System.out.println(test(""+c[i]));
}
}
public static String test(String pa){
boolean is_con = true;
String result = "";
while(is_con){
String a = pa;
String b = getRandomJianHan(1);
if(translation(a).equals(translation(b))){
if(a.equals(b)){
continue;
}
//System.out.println(a);
//System.out.println(b);
//System.out.println(i);
result = b;
is_con = false;
}else{
is_con = true;
}
}
return result;
}
// 將字串轉移為ASCII碼
public static String getCnASCII(String cnStr) {
StringBuffer strBuf = new StringBuffer();
byte[] bGBK = cnStr.getBytes();
for (int i = 0; i < bGBK.length; i++) {
strBuf.append(Integer.toHexString(bGBK[i] & 0xff));
}
return strBuf.toString();
}
public static String getRandomJianHan(int len)
{
String ret="";
for(int i=0;i<len;i++){
String str = null;
int hightPos, lowPos; // 定義高低位
Random random = new Random();
hightPos = (176 + Math.abs(random.nextInt(39))); //獲取高位值
lowPos = (161 + Math.abs(random.nextInt(93))); //獲取低位值
byte[] b = new byte[2];
b[0] = (new Integer(hightPos).byteValue());
b[1] = (new Integer(lowPos).byteValue());
try
{
str = new String(b, "GBk"); //轉成中文
}
catch (UnsupportedEncodingException ex)
{
ex.printStackTrace();
}
ret+=str;
}
return ret;
}
public static String translation(String src) {
char[] t1 = null;
t1 = src.toCharArray();
String[] t2 = new String[t1.length];
HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
t3.setVCharType(HanyuPinyinVCharType.WITH_V);
String t4 = "";
int t0 = t1.length;
try {
for (int i = 0; i < t0; i++) {
// 判斷是否為漢字字元
if (java.lang.Character.toString(t1[i]).matches(
"[\\u4E00-\\u9FA5]+")) {
t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);
t4 += t2[0];
} else
t4 += java.lang.Character.toString(t1[i]);
}
// System.out.println(t4);
return t4;
} catch (BadHanyuPinyinOutputFormatCombination e1) {
e1.printStackTrace();
}
return t4;
}
}