Mercer
Mercer

Reputation: 9986

Generate a random Alphanumeric String without some characters

I want to generate a random Alphanumeric String. I want to exlude some characters from my string

l, i, o and the number 0

For the moment i have this code:

import org.apache.commons.lang.RandomStringUtils;
...
numberFile = RandomStringUtils.randomAlphanumeric( 5 );

Upvotes: 2

Views: 6793

Answers (3)

Markus Benko
Markus Benko

Reputation: 1507

Turning Davide Spataro's answer into code without using any 3rd party library could look like this:

private static final String ALPHABET = "123456789abcdefghjkmnpqrstuvwxyz";

public static String generateRandomString(int length) {
    Random random = ThreadLocalRandom.current();
    int alphabetLength = ALPHABET.length();
    char[] chars = new char[length];
    for (int i = 0; i < length; i++)
        chars[i] = ALPHABET.charAt(random.nextInt(alphabetLength));
    return String.valueOf(chars);
}

Or alternatively a Java 8 Stream based approach:

public static String generateRandomStringJava8(int length) {
    return IntStream.range(0, length)
            .map(i -> ThreadLocalRandom.current().nextInt(ALPHABET.length()))
            .mapToObj(i -> ALPHABET.substring(i, i + 1))
            .collect(Collectors.joining());
}

Both methods generate Strings of given length by picking length random characters from the static ALPHABET.

Upvotes: 1

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37594

Since you are using RandomStringUtils you might aswell use the designated RandomStringUtils#random method for that.

public static String random(int count,
                            int start,
                            int end,
                            boolean letters,
                            boolean numbers,
                            char... chars)

Parameters:
count - the length of random string to create
start - the position in set of chars to start at
end - the position in set of chars to end before
letters - only allow letters?
numbers - only allow numbers?
chars - the set of chars to choose randoms from. If null, then it will use the set of all chars.

See the docs here.

Upvotes: 6

Davide Spataro
Davide Spataro

Reputation: 7482

Construct an array with the element from which your string want to be built upon.

Let's say C={a,b,c,d....,1,2,3..} has size n

Generate n random numbers in the range [0,n-1], for example D={3,5,1,0,2..}. Now if you build a string s from D as follows:s[i] = C[D[i]] what you get is a random string from a set of chars defined in C, which a guess is exactly what you want.

You can easily make C such that it does not contain the set of characters you don't want to appear in your random String.

Upvotes: 4

Related Questions