随机生成N个由数字和小写字母组成的字符窜

public class Consts
{
    /// 
    /// 26个小写的英文字符
    /// 
    public static readonly string[] strsLeter = new string[] { "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" };

    /// 
    /// 0,1,2,3,4,5,6,7,8,9
    /// 
    public static readonly string[] strsNum = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
}


public class Utill
{
/// 
    /// 随机生成N个字符
    /// 
    /// 参数长度介于6和50之间
    /// 
    public static string CreateRandomStr(int size)
    {
        if (size < 6 || size > 50)
            return Consts.strUPwd;
        //字母个数
        int leter = size / 2;
        //数字个数
        int num = size - leter;


        Random ran = new Random();
        string pwd = string.Empty;
        int index = -1;
        //生成随机的字母
        for (int i = 0; i < leter; i++)
        {
            index = ran.Next(0, Consts.strsLeter.Length - 1);
            pwd += Consts.strsLeter[index];
        }
        //生成随机的数字
        for (int i = 0; i < num; i++)
        {
            index = ran.Next(0, Consts.strsNum.Length - 1);
            pwd += Consts.strsNum[index];
        }
        //打乱字母和数字的顺序
        string tmpPwd = pwd;
        pwd = string.Empty;
        while (tmpPwd.Trim().Length > 0)
        {
            index = ran.Next(0, tmpPwd.Length - 1);
            pwd += tmpPwd[index];
            tmpPwd=tmpPwd.Remove(index, 1);
        }
        return pwd;
    }
}


你可能感兴趣的:(随机生成N个由数字和小写字母组成的字符窜)