Tuesday, June 19, 2012

Generating random Java strings

I found lots of misfitting advice searching Google for how to generate random strings in Java. The misfits assumed I was generating unique keys, often for web page cookies.

What I searched for was random Java strings along the lines of new Random().nextInt(), to use for probabilistic testing, but I failed to find this so I rolled my own.

Not a thing of beauty, but accomplished by goal. Hopefully someone might find this useful:

String randomString(final Random random,
        final int minLength, final int maxLength) {
    final int length = random.nextInt(maxLength - minLength) + minLength;
    final char[] chars = new char[length];
    for (int i = 0, x = chars.length; i < x; )
        do {
            final int cp = random.nextInt(0x10FFFF + 1);
            if (!Character.isDefined(cp))
                continue;
            final char[] chs = Character.toChars(cp);
            if (chs.length > x - i)
                continue;
            for (final char ch : chs)
                chars[i++] = ch;
            break;
        } while (true);

    return new String(chars);
}

To examine what you get back, consider Character.UnicodeBlock.of(int codePoint).

No comments: