Creates random string of characters and digits. - Java java.util

Java examples for java.util:Random String

Description

Creates random string of characters and digits.

Demo Code


import java.util.Random;

public class Main{
    protected static final Random rnd = new Random();
    protected static final char[] ALPHA_NUMERIC_RANGE = new char[] { '0',
            '9', 'A', 'Z', 'a', 'z' };
    /**//from   ww  w . ja va 2  s  .c o m
     * Creates random string of characters and digits.
     */
    public static String randomAlphaNumeric(int count) {
        return randomRanges(count, ALPHA_NUMERIC_RANGE);
    }
    /**
     * Creates random string whose length is the number of characters specified.
     * Characters are chosen from the multiple sets defined by range pairs. All
     * ranges must be in acceding order.
     */
    public static String randomRanges(int count, char... ranges) {
        if (count == 0 || ranges == null) {
            return StringUtil.EMPTY_STRING;
        }
        int i = 0;
        int len = 0;
        int lens[] = new int[ranges.length];
        while (i < ranges.length) {
            int gap = ranges[i + 1] - ranges[i] + 1;
            len += gap;
            lens[i] = len;
            i += 2;
        }

        char[] result = new char[count];
        while (count-- > 0) {
            char c = 0;
            int r = rnd.nextInt(len);
            for (i = 0; i < ranges.length; i += 2) {
                if (r < lens[i]) {
                    r += ranges[i];
                    if (i != 0) {
                        r -= lens[i - 2];
                    }
                    c = (char) r;
                    break;
                }
            }
            result[count] = c;
        }
        return new String(result);
    }
}

Related Tutorials