本文主要通过Java 来随机生成一个中文名字,在写代码之前,首先要了解两个比较重要的知识点:
下面来自百度百科的解释:中国人的姓名,是由汉字来组成,汉族人是用汉字进行取名,其他民族的姓名则音译为汉字表示,也有些为自己另取汉名。
总结:汉字名字 + 中文姓氏 = 中国人的姓名
在Unicode 5.0 的99089 个字符中,有71226 个字符是与汉字有关的,而汉字的编码范围是在0x4E00 ~ 0x9FBB
这里直接使用中国的百家姓,通过random 随机生成一下【下标值】来挑选,由于篇幅关系,这里只列了几个,详细的可以自行搜索。
/** * 百家姓 */ 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]; 复制代码
这里的名字统一设置为由2 ~ 3 位的汉字组成,而汉字的生成是从Unicode 的编码范围中随机挑取。
private static String getChineseCharacter() { int random = new Random().nextInt(0x9FBB - 0x4E00 + 1) + 0x4E00; return new String(new char[]{(char) (random)});} 复制代码
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()); } } 复制代码
由于从Unicode 随机挑取出来的汉字过于生僻,所以笔者直接从三字经中挑选汉字作为名字。 由于篇幅原因,所以只举例部分
private static final String NAME = "人之初性本善性相近习相远苟不教性乃迁教之道贵以专昔孟母择邻处子不学断机杼窦燕"; private static String getChineseCharacterFromBook() { int random = new Random().nextInt(NAME.length()); return String.valueOf(NAME.charAt(random)); }
原文链接:https://juejin.cn/post/6972096604186607623