日期:2014-05-17  浏览次数:20493 次

求随机生成一个字符串写法
刚自己写了一下,每次都不能生成唯一的数字.有重复
所以恳请大家帮忙
需求是:共12位字符,前四位为字母,后四位为数字!

------解决方案--------------------
C# code
                Random ran=new Random();
                string s="";
                int num=0;
                int i=0;
                do
                {
                    num=ran.Next(1,34);
                    if(s!="")
                    {
                        if(s.IndexOf(num.ToString()+",")==0)
                        {
                        
                        }
                        else if(s.IndexOf(","+num.ToString()+",")>0)
                        {
                        
                        }
                        else
                        {
                            s+=num.ToString()+",";
                            i++;
                        }
                    }
                    else
                    {
                        s+=num.ToString()+",";
                        i++;
                    }
                }while(i!=6);
                Response.Write(s);

------解决方案--------------------
int number;
char code;
string checkCode = String.Empty;

System.Random random = new Random();

for (int i = 0; i < 4; i++)
{
number = random.Next();

if (number % 2 == 0)
{
code = (char)('0' + (char)(number % 10));
checkCode += code.ToString();
}
else
{
i--;
}
}
for (int j = 0; j < 4; j++)
{
number = random.Next();
if (number % 2 != 0)
{
code = (char)('A' + (char)(number % 26));
checkCode += code.ToString();
}
else
{
j--;
}
}
Response.Write(checkCode.ToString());
------解决方案--------------------
要求不高的话,直接拿系统随机返回的字串就可以了.


C# code
    public static string getRndString(int len)
    {
        return System.Guid.NewGuid().ToString().Substring(0, len);   
    }

    string x = getRndString(6);

------解决方案--------------------
private string getString()
{
string str = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,p,q,r,s,t,u,v,w,x,y,z";
string strString = null;
string strNumber = null;
string[] strs = str.Split(',');
Random rand = new Random();
for (int i = 0; i < 4; i++)
{
strString += strs[rand.Next(25)].ToString();
strNumber += rand.Next(10).ToString();
}

return strNumber + strString;
}