Forums Register Login

Random String (Hash)

+Pie Number of slices to send: Send
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 ]
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
java.util.Random provides some more ways to create random numbers.
+Pie Number of slices to send: Send
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.
Poop goes in a willow feeder. Wipe with this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 1450 times.
Similar Threads
HashCode to String
Suggestion needed on digesting passwords
correct hashCode( ) method
Generating Unique Random Numbers in JAVA
String hash
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 06:01:26.