Link to home
Start Free TrialLog in
Avatar of Shanmugam Rajagopal
Shanmugam Rajagopal

asked on

generate random string with pattern in C#

Hi, How to generate random string with below pattern in C#

MAX LENGTH - 15
NUMERIC- 1
LOWER CASE - 1
UPPER CASE - 1
NON-APLHA NUMERIC - 1
Avatar of hilltop
hilltop
Flag of United States of America image

You could give this a shot.

 var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@#$%^&*(){}[]|?";
 var CharsA = new char[15];
var random = new Random();
 for (int i = 0; i < CharsA.Length; i++)
  {
 CharsA[i] = chars[random.Next(chars.Length)];
  }
 var final = new String(CharsA);

Open in new window


Or like this.

            var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
            var chars1 = "0123456789";
            var chars2 = "@#$%^&*(){}[]|?";
            var CharsA = new char[15];
            var random = new Random();
            for (int i = 0; i < CharsA.Length; i++)
            {
                if (i <= 12)
                {
                    CharsA[i] = chars[random.Next(chars.Length)];
                }
                if (i == 13)
                {
                    CharsA[i] = chars1[random.Next(chars1.Length)];
                }
                if (i == 14)
                {
                    CharsA[i] = chars2[random.Next(chars2.Length)];
                }
            }
            var final = new String(CharsA);

Open in new window

MAX LENGTH - 15
NUMERIC- 1
LOWER CASE - 1
UPPER CASE - 1
NON-APLHA NUMERIC - 1

Do you mean the 15 character string must have at least 1 of Numeric ,Upper Case, Lower Case, Non-Alpha Numeric. Or a string of up to 15 Characters meeting the above rules
ASKER CERTIFIED SOLUTION
Avatar of Gustav Brock
Gustav Brock
Flag of Denmark image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Shanmugam Rajagopal
Shanmugam Rajagopal

ASKER

Thanks All for posting different solutions. I will try and update which works well.

Mr David, yes (15 character string must have at least 1 of Numeric ,Upper Case, Lower Case, Non-Alpha Numeric).
Thanks everyone for your help