Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

Random String (Hash)

Charles OBrien
Greenhorn
Posts: 10
Okay, I am proposed with yet another simple problem.
I am trying to figure out a way to create a random string. This string should be around 12 characters long and can consist of letters and numbers.
The purpose of this hash is to serve as a unique identifier for a user. Simmilar to a session, but different.
[Edit: This is for a servlet]
Any help appreciated.
[ June 11, 2002: Message edited by: Charles OBrien ]

Jessica Sant
Sheriff
Posts: 4313
why not use the Math.random() function to generate a random number for yourself. Then convert that into a char... concatenate the char's together to make a String.
Remember that Math.random() generates a decimal number between 0 and 1 so you'll need to multiply it by some integer to make it a valid int to be converted to a char.

Ilja Preuss
author
Sheriff
Posts: 14112
java.util.Random provides some more ways to create random numbers.

Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
I had to do something like this and this is what I did:
1) Create an array of characters of all the valid characters that you want in the generated String.
char[] c = {'A', 'a', 'B', etc...}
2) Generate a random number from zero to 1 less than the length of the char array
3) Use that number as an index into the array to pick a random character
4) Use that character as the first character of your string
5) Repeat 2 and 3, adding the chosen charaacter to your String until you have all that characters you need for your string.
The nice thing about this is that you can control exactly what characters are allowed in your string. We eliminated characters that look too much alike such as the number one and lower-case letter 'L'; zero and the upper case letter 'O'. ( 1 and l ; 0 and O). In some fonts they are identical.