Java 隨機生成中文名字

導論

本文主要通過Java 來隨機生成一箇中文名字,在寫代碼之前,首先要了解兩個比較重要的知識點:

中文名字的構成

來自百度百科的解釋:中國人的姓名,是以漢字表示,漢族人是用漢字進行取名,其他民族的姓名則音譯為漢字表示,也有些為自己另取漢名。名字與中文姓氏一起構成了中國人的姓名。

Unicode 中的行字

在Unicode 5.0 的99089 個字符中,有71226 個字符是與漢字有關的,而漢字的編碼範圍是在0x4E00 ~ 0x9FBB

代碼實現

生成姓氏

這裡直接使用中國的百家姓,通過random 隨機生成一下下標值來挑選,由於篇幅關係,這裡只列了幾個,詳細的可以自行搜索。

<code>/** * 百家姓 */private final static String[] LAST_NAME = {"趙", "錢", "孫", "李", "周", "吳", "鄭", "王", "馮", "陳", "褚", "衛", "蔣", "沈", "韓", "楊", "朱", "秦", "尤", "許", "何", "呂", "施", "張", "孔", "曹", "嚴", "華", "金", "魏", "陶", "姜", "戚", "謝", "鄒", "喻", "柏", "水", "竇", "章", "雲", "蘇", "潘", "葛", "奚", "範", "彭", "郎", "魯", "韋", "昌", "馬", "苗", "鳳", "花", "方", "俞", "任", "袁", "柳", "酆", "鮑", "史", "唐", "費", "廉", "岑", "薛", "雷", "賀", "倪", "湯", "滕", "殷",  "羅", "畢", "郝", "鄔", "安", "常", "樂", "於", "時", "傅"};

//獲得一個隨機的姓氏
Random random = new Random(System.currentTimeMillis());
int index = random.nextInt(LAST_NAME.length - 1);
String name = LAST_NAME[index];
/<code>

生成名字

這裡的名字統一設置為由2 ~ 3 位的漢字組成,而漢字的生成是從Unicode 的編碼範圍中隨機挑取。

<code>private static String getChineseCharacter() {   
int random = new Random().nextInt(0x9FBB - 0x4E00 + 1) + 0x4E00;
return new String(new char[]{(char) (random)});}
/<code>

完整代碼

<code>public class ChineseNameUtils {   
/**
* 百家姓
*/
private final static String[] LAST_NAME = {"趙", "錢", "孫", "李", "周", "吳", "鄭", "王", "馮", "陳", "褚"};

public static String getChineseName() {
//獲得一個隨機的姓氏
Random random = new Random(System.currentTimeMillis());
int index = random.nextInt(LAST_NAME.length - 1);
String name = LAST_NAME[index];
/* 從常用字中選取一個或兩個字作為名 */
if (random.nextBoolean()) {
name += getChineseCharacter() +
getChineseCharacter();
} else {
name += getChineseCharacter();
}
return name;
}

private static String getChineseCharacter() {
int random = new Random().nextInt(0x9FBB - 0x4E00 + 1) + 0x4E00;
return new String(new char[]{(char) (random)});
}

public static void main(String[] args) {
System.out.println(getChineseName());
}

}


/<code>

改進

直接從Unicode 隨機挑取出來的漢字過於生僻,所以筆者直接從三字經中挑選漢字作為名字。由於篇幅原因,所以只舉例部分

<code>private static final String NAME = "人之初性本善性相近習相遠苟不教性乃遷教之道貴以專昔孟母擇鄰處子不學斷機杼竇燕";

private static String getChineseCharacterFromBook() {
int random = new Random().nextInt(NAME.length());
return String.valueOf(NAME.charAt(random));
}


輸出:弘謝宜/<code>


分享到:


相關文章: