• Twitter
  • Facebook
  • Google+
  • Instagram
  • Youtube

Wednesday, February 27, 2008

Generate a random alpha numeric string from given length

Generate a random alpha numeric string from given length.
==================================================

/// <summary>

/// Generate a random alpha numeric string from given length.
/// Author : Abhishek Joshi
/// 24 Feb, 2008
/// </summary>
/// <param name="iLength"></param>
/// <returns>Enter output string Length.</returns>
public static string GenerateAlphNumericCode(int iLength)
{
int iZero, iNine, iA, iZ, iCount = 0, iRandNum;
string sRandomString ;

// we'll need random characters, so a Random object
// should probably be created...
Random rRandom = new Random(System.DateTime.Now.Millisecond);
// convert characters into their integer equivalents (their ASCII values)
iZero = (int) '0';
iNine = (int) '9';
iA = (int) 'A';
iZ = (int)'Z';

// initialize our return string for use in the following loop
sRandomString = string.Empty;

// now we loop as many times as is necessary to build the string
// length we want
while (iCount < iLength)
{
// we fetch a random number between our high and low values
iRandNum = rRandom.Next(iZero, iZ);

// here's the cool part: we inspect the value of the random number,
// and if it matches one of the legal values that we've decided upon,
// we convert the number to a character and add it to our string
if (((iRandNum >= iZero) && (iRandNum <= iNine) || (iRandNum >= iA) && (iRandNum <= iZ)))
{
sRandomString = sRandomString + Convert.ToChar(iRandNum);
iCount = iCount + 1;

}
}
// finally, our random character string should be built, so we return it
return sRandomString;
}

That's it !
Hope you will like it.

2 comments:

Shadab said...

I have tried ur code in C#. got the excellent result which i desired....

ghost said...

Great code, thanks, worked perfectly.

Contact

Get in touch with me


Adress/Street

12 Street West Victoria 1234 Australia

Phone number

+(12) 3456 789

Website

www.johnsmith.com