Tuesday, 17 May 2016

Alphanumeric string generator

#CodeSnippet #CSharp #theMazeRunner #CRM How to create an alphanumeric string for use as a password or an Account Number On many occasions you may need to create a unique password or identifier string. There are already methods out there to create random strings of a given or variable length. I have taken the concept and modified it to suit my own need. Basically I create an array of characters and an array of numbers (removing any that may be easy to confuse). I then pass a parameter to determine how long the string will be. Finally I use a combination of the char string and a string of numbers to create my desired length output string (consisting in this case of 3 letters followed by 3 numbers followed by 3 letters). This particular code snippet is C# and is used to generate my web service. You can adapt it to other languages or make it part of your existing C# Library. [pre class="brush:csharp" title="Alphanumeric string generator"] using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace utilLib { public class AccNumGen { // what's available; I have removed the Letters 'I' and 'O' public static string possibleChars = "ABCDEFGHJKLMNPQRSTUVWXYZ"; // to help readability I have also removed 0 and 1 public static string possibleNums = "23456789"; // optimized (?) what's available public static char[] possibleCharsArray = possibleChars.ToCharArray(); public static char[] possibleNumsArray = possibleNums.ToCharArray(); // optimized (precalculated) count public static int possibleCharsAvailable = possibleChars.Length; public static int possibleNumsAvailable = possibleNums.Length; // shared randomization thingy public static Random random = new Random(); public string getRandomChars(int num) { /* use the random method to select a char and repeat * for the numbe of times passed in as a parameter */ var result = new char[num]; while (num-- > 0) { result[num] = possibleCharsArray[random.Next(possibleCharsAvailable)]; } return new string(result); } public string getRandomNums(int num) { var result = new char[num]; while (num-- > 0) { result[num] = possibleNumsArray[random.Next(possibleNumsAvailable)]; } return new string(result); } public string createAccNum() { // build the desired pattern using combination of chars and numbers // in this case I have 3 Chars then 3 numbers then 3 chars var AccNum = getRandomChars(3) + getRandomNums(3) + getRandomChars(3); return AccNum; } } } [/pre]

No comments:

Post a Comment