在 Java 中创建具有 A-Z 和 0-9 的随机字符串

2022-08-31 12:18:21

正如标题所暗示的那样,我需要创建一个随机的,长度为17个字符的ID。类似于“”。字母和数字的顺序也是随机的。我想创建一个带有字母A-Z的数组和一个随机设置为的“check”变量。并在一个循环中;AJB53JHS232ERO0H11-2

Randomize 'check' to 1-2.
If (check == 1) then the character is a letter.
Pick a random index from the letters array.
else
Pick a random number.

但我觉得有一种更简单的方法可以做到这一点。有吗?


答案 1

在这里,您可以使用我的方法生成随机字符串

protected String getSaltString() {
        String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        StringBuilder salt = new StringBuilder();
        Random rnd = new Random();
        while (salt.length() < 18) { // length of the random string.
            int index = (int) (rnd.nextFloat() * SALTCHARS.length());
            salt.append(SALTCHARS.charAt(index));
        }
        String saltStr = salt.toString();
        return saltStr;

    }

上述方法从我的包中用于生成用于登录目的的盐字符串。


答案 2

来自Apache commons-lang的RandomStringUtils可能会有所帮助:

RandomStringUtils.randomAlphanumeric(17).toUpperCase()

2017年更新:已被弃用,您现在应该使用RandomStringGeneratorRandomStringUtils


推荐