Generating Alphanumeric random string in Java

PrivusGuru picture PrivusGuru · Aug 6, 2013 · Viewed 27.8k times · Source

I am using String Builder from another answer, but I can't use anything but alpha/numeric, no whitespace, punctuation, etc. Can you explain how to limit the character set in this code? Also, how do I insure it is ALWAYS 30 characters long?

     Random generator = new Random();
    StringBuilder stringBuilder = new StringBuilder();
    int Length = 30;
    char tempChar ;
    for (int i = 0; i < Length; i++){
        tempChar = (char) (generator.nextInt(96) + 32);
        stringBuilder.append(tempChar);

I have looked at most of the other answers, and can't figure out a solution to this. Thanks. Don't yell at me if this is a duplicate. Most of the answers don't explain which part of the code controls how long the generated number is or where to adjust the character set.

I also tried stringBuilder.Replace(' ', '1'), which might have worked, but eclipse says there is no method for Replace for StringBuilder.

Answer

zapl picture zapl · Aug 6, 2013

If you want to control the characterset and length take for example

public static String randomString(char[] characterSet, int length) {
    Random random = new SecureRandom();
    char[] result = new char[length];
    for (int i = 0; i < result.length; i++) {
        // picks a random index out of character set > random character
        int randomCharIndex = random.nextInt(characterSet.length);
        result[i] = characterSet[randomCharIndex];
    }
    return new String(result);
}

and combine with

char[] CHARSET_AZ_09 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();

to specify the characterset.

It's not based on StringBuilder since you know the length and don't need all the overhead.

It allocates a char[] array of the correct size, then fills each cell in that array with a randomly chosen character from the input array.

more example use here: http://ideone.com/xvIZcd