Can I use Apache's common-text RandomStringGenerator
to generate random alphanumeric strings (numbers and lowercase/uppercase letters)?
To generate a random string of alphanumeric characters (alphanumeric sequence), start by specifying which alphabet to use. "Alphabet" here means simply the collection (or 'bag') of characters from which the random alphanumeric generator has to pick.
In the Insert Random Data dialog box, click String tab, and choose the type of characters as you need, then specify the length of the string in the String length box, and finally click the OK button. See screenshot: Then the selected range has been filled with random character strings.
RandomStringGenerator generator = new RandomStringGenerator.Builder()
.selectFrom("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray())
.build();
I kind of prefer this way rather than generating character codes and filtering out ones I don't want. And implicitly assuming that '0'..'z' includes all the codes I want, including capital letters (based on the ascii code chart).
In addition, depending on the application (eg password generation), you might want to use a CSPRNG (secure PRNG) seeded by a true-randomness source:
.usingRandom(new SecureRandom()::nextInt)
The default SecureRandom seed is from a true-randomness source of OS hardware device entropy.
Yes, using the following code:
import static org.apache.commons.text.CharacterPredicates.DIGITS;
import static org.apache.commons.text.CharacterPredicates.LETTERS;
// ...
RandomStringGenerator generator = new RandomStringGenerator.Builder()
.withinRange('0', 'z')
.filteredBy(LETTERS, DIGITS)
.build();
I use this:
static char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'q', 'w', 'e', 'r', 't', 'z', 'u', 'i', 'o', 'p', 'a', 's',
'd', 'f', 'g', 'h', 'j', 'k', 'l', 'y', 'x', 'c', 'v', 'b', 'n', 'm', 'Q', 'W', 'E', 'R', 'T', 'Z', 'U', 'I', 'O', 'P', 'A',
'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Y', 'X', 'C', 'V', 'B', 'N', 'M' };
private static String randomString(int length) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < length; i++) {
stringBuilder.append(chars[new Random().nextInt(chars.length)]);
}
return stringBuilder.toString();
}
or
private static String randomString(int length) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < length; i++) {
switch (new Random().nextInt(3)) {
case 0:
stringBuilder.append((char) (new Random().nextInt(9) + 48));
break;
case 1:
stringBuilder.append((char) (new Random().nextInt(25) + 65));
break;
case 2:
stringBuilder.append((char) (new Random().nextInt(25) + 97));
break;
default:
break;
}
}
return stringBuilder.toString();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With