How to generate a random string, and specify the length you want, or better generate unique string on specification you want

前端 未结 11 2325
一生所求
一生所求 2020-12-24 06:24

There is a library to generate Random numbers, so why isn\'t there a library for generation of random strings?

In other words how to generate a random string, and sp

11条回答
  •  北海茫月
    2020-12-24 07:19

    How about-

        static Random rd = new Random();
        internal static string CreateString(int stringLength)
        {
            const string allowedChars = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789!@$?_-";
            char[] chars = new char[stringLength];
    
            for (int i = 0; i < stringLength; i++)
            {
                chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
            }
    
            return new string(chars);
        }
    

提交回复
热议问题