C#獲取相鄰字符不相等的隨機字符串(0~9,A~Z,或自定義)

        /// <summary>
        /// 生成隨機數
        /// </summary>
        /// <param name="codeLen">數據的長度</param>
        /// <returns></returns>
        public string CreateRandomCode(int codeLen)
        {
            string allChar = "0,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";// 若想生成驗證碼則一般會去掉相似的字符,如:O與0、I與1
            string[] allCharAry = allChar.Split(',');
            string randomCode = "";
            int temp = -1;
            Random rand = new Random();
            for (int i = 0; i < codeLen; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * ((int)DateTime.Now.Ticks));// 保證隨機性跟嚴謹
                }
                int t = rand.Next(35);// allChar數組索引最大值
                if (temp == t)
                {
                    return CreateRandomCode(codeLen);//防止隨機字符串中兩個相鄰的字符相等
                }
                temp = t;
                randomCode += allCharAry[t];
            }
            return randomCode;
        }數組

相關文章
相關標籤/搜索