【C#】随机生成不重复的英文名字代码
起初是因为某电商平台注册新号需要邮箱,但是不需要验证码,所以写了一个邮箱号随机生成的软件,格式是: firstName+lastName+随机字符+@xxx.xxx主要分享一下我这边用到的随机生成不重复英文名字的代码
//调用此函数生成2次拼接作为一个完整英文名
private string GenerateSurname()
{
string name = string.Empty;
string[] currentConsonant;
string[] vowels = "a,a,a,a,a,e,e,e,e,e,e,e,e,e,e,e,i,i,i,o,o,o,u,y,ee,ee,ea,ea,ey,eau,eigh,oa,oo,ou,ough,ay".Split(',');
string[] commonConsonants = "s,s,s,s,t,t,t,t,t,n,n,r,l,d,sm,sl,sh,sh,th,th,th".Split(',');
string[] averageConsonants = "sh,sh,st,st,b,c,f,g,h,k,l,m,p,p,ph,wh".Split(',');
string[] middleConsonants = "x,ss,ss,ch,ch,ck,ck,dd,kn,rt,gh,mm,nd,nd,nn,pp,ps,tt,ff,rr,rk,mp,ll".Split(','); //Can't start
string[] rareConsonants = "j,j,j,v,v,w,w,w,z,qu,qu".Split(',');
Random rng = new Random(Guid.NewGuid().GetHashCode()); //http://codebetter.com/blogs/59496.aspx
int[] lengthArray = new int[] { 2, 2, 2, 2, 2, 2, 3, 3, 3, 4 }; //Favor shorter names but allow longer ones
int length = lengthArray;
for (int i = 0; i < length; i++)
{
int letterType = rng.Next(1000);
if (letterType < 775) currentConsonant = commonConsonants;
else if (letterType < 875 && i > 0) currentConsonant = middleConsonants;
else if (letterType < 985) currentConsonant = averageConsonants;
else currentConsonant = rareConsonants;
name += currentConsonant;
name += vowels;
if (name.Length > 4 && rng.Next(1000) < 800) break; //Getting long, must roll to save
if (name.Length > 6 && rng.Next(1000) < 950) break; //Really long, roll again to save
if (name.Length > 7) break; //Probably ridiculous, stop building and add ending
}
int endingType = rng.Next(1000);
if (name.Length > 6)
endingType -= (name.Length * 25); //Don't add long endings if already long
else
endingType += (name.Length * 10); //Favor long endings if short
if (endingType < 400) { } // Ends with vowel
else if (endingType < 775) name += commonConsonants;
else if (endingType < 825) name += averageConsonants;
else if (endingType < 840) name += "ski";
else if (endingType < 860) name += "son";
else if (Regex.IsMatch(name, "(.+)(ay|e|ee|ea|oo)$") || name.Length < 5)
{
name = "Mc" + name.Substring(0, 1).ToUpper() + name.Substring(1);
return name;
}
else name += "ez";
name = name.Substring(0, 1).ToUpper() + name.Substring(1); //Capitalize first letter
return name;
} Csharpyyds
页:
[1]