C#生成不重复随机字符串类
本文实例讲述了C#生成不重复随机字符串类。分享给大家供大家参考。具体如下:
这个C#类用于随机产生不重复的字符串,可以指定字符串范围,可以指定要产生字符串的长度
usingSystem;
namespaceDotNet.Utilities
{
publicclassRandomOperate
{
//一:随机生成不重复数字字符串
privateintrep=0;
publicstringGenerateCheckCodeNum(intcodeCount)
{
stringstr=string.Empty;
longnum2=DateTime.Now.Ticks+this.rep;
this.rep++;
Randomrandom=newRandom(((int)(((ulong)num2)&0xffffffffL))|((int)(num2>>this.rep)));
for(inti=0;i<codeCount;i++)
{
intnum=random.Next();
str=str+((char)(0x30+((ushort)(num%10)))).ToString();
}
returnstr;
}
//方法二:随机生成字符串(数字和字母混和)
publicstringGenerateCheckCode(intcodeCount)
{
stringstr=string.Empty;
longnum2=DateTime.Now.Ticks+this.rep;
this.rep++;
Randomrandom=newRandom(((int)(((ulong)num2)&0xffffffffL))|((int)(num2>>this.rep)));
for(inti=0;i<codeCount;i++)
{
charch;
intnum=random.Next();
if((num%2)==0)
{
ch=(char)(0x30+((ushort)(num%10)));
}
else
{
ch=(char)(0x41+((ushort)(num%0x1a)));
}
str=str+ch.ToString();
}
returnstr;
}
#region
///<summary>
///从字符串里随机得到,规定个数的字符串.
///</summary>
///<paramname="allChar"></param>
///<paramname="CodeCount"></param>
///<returns></returns>
privatestringGetRandomCode(stringallChar,intCodeCount)
{
//stringallChar="1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,i,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
string[]allCharArray=allChar.Split(',');
stringRandomCode="";
inttemp=-1;
Randomrand=newRandom();
for(inti=0;i<CodeCount;i++)
{
if(temp!=-1)
{
rand=newRandom(temp*i*((int)DateTime.Now.Ticks));
}
intt=rand.Next(allCharArray.Length-1);
while(temp==t)
{
t=rand.Next(allCharArray.Length-1);
}
temp=t;
RandomCode+=allCharArray[t];
}
returnRandomCode;
}
#endregion
}
}
希望本文所述对大家的C#程序设计有所帮助。