项目在测试时,有时候需要生成大量的测试数据,如果是数字之类的还比较好办,直接用 Random 类随机生成就行了,如果是人名之类的就要麻烦一些,总不能把人的名字也随机生成为 abc 之类的吧,于是就有了下面这个“中文姓名生成器".
思路其实很简单,把姓名分为”姓“和”名“两部分。
”姓“的数据从百家姓中找,”名“的资料也是网上搜搜就行了,比如男孩一般叫”强“、”国“、”浩“。。。女孩一般叫”丽“、”霞“、”燕“等等。然后把这两部分随机组合就行了。
看看程序截图,是不是有模有样?呵呵
附上代码和程序 下载程序
public class NameGenerator { public string[] FirstNames { get; set; } public string[] BoyWords { get; set; } public string[] GirlWords { get; set; } Random _rand = new Random((int)DateTime.Now.Ticks); public NameGenerator() { FirstNames = new[] { "赵","钱","孙","李","周","吴","郑","王","冯","陈","褚","卫","蒋","沈","韩","杨","朱","秦","尤","许","何","吕","施","张","孔","曹","严","华","金","魏","陶","姜","戚","谢","邹","水","昌","马","苗","凤","花","方","俞","任","袁","柳","鲍","史","唐","费","岑","薛","雷","贺","倪","汤","殷","罗","毕","郝","邬","安","常","乐","于","时","齐","康","伍","余","元","顾","孟","黄", "欧阳","夏侯","皇甫","上官"}; BoyWords = new[] { "刚","强","仁","发","民","国","忠","艺","文","德","志","智","辉","华","军","生","裕","健","炎","宏","毅","坚","石","超","鹏","亮","锦","家","春","磊","勇","正","东","南","斌","武","友","祖","颂","小","宇","兴","波","荣","峰","祥","思","振","海","凯","远","汉","桥","松","柏","利","大"}; GirlWords = new[] { "花","华","芳","芬","燕","虹","菁","丽","娟","莘","苹","红","玉","妙","丹","芸","香","蕾","兰","慧","玲","静","茹","怡","紫"}; } public string generate(string first_name, int sex, int length) { var index = 0; if (string.IsNullOrEmpty(first_name)) { index = _rand.Next(FirstNames.Length); first_name = FirstNames[index]; } var name = first_name; if (sex < 0 || sex > 1) { sex = _rand.Next(2); } if (length < 1) { length = _rand.Next(2) + 1; } for (int i = 0; i < length; i++) { if (sex == 0) { index = _rand.Next(BoyWords.Length); name += BoyWords[index]; } else { index = _rand.Next(GirlWords.Length); name += GirlWords[index]; } } return name; }