Random string of given length

From Stack Overflow
Jump to: navigation, search
    public static Random randomGenerator = new Random();
    // Capital letters with confusing characters removed..."1" looks like "I" and "l", etc
    public static final String randomCharacterSpace = 
        "ABCDEFGHJKMNPQRSTUVWXYZ23456789";

    /**
     * Return a random string consisting of letters and numbers
     *
     *@param length length of the string
     *@result the random string
     */
    public static String randomString(int length)
    {
        StringBuffer result = new StringBuffer();
        int max = randomCharacterSpace.length();
        while (--length >= 0)
            result.append(randomCharacterSpace.charAt(Math.abs(randomGenerator.nextInt() % max)));
        return result.toString();
    }

Personal tools