简单的中文姓名生成器

项目在测试时,有时候需要生成大量的测试数据,如果是数字之类的还比较好办,直接用 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;
        }

 

posted @ 2013-02-18 17:59  在天空飞翔  阅读(4059)  评论(1编辑  收藏  举报