在 Java 中创建一个带有 AZ 和 0-9 的随机字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20536566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:36:13  来源:igfitidea点击:

Creating a random string with A-Z and 0-9 in Java

javarandom

提问by cbt

As the title suggest I need to create a random, 17 characters long, ID. Something like "AJB53JHS232ERO0H1". The order of letters and numbers is also random. I thought of creating an array with letters A-Z and a 'check' variable that randoms to 1-2. And in a loop;

正如标题所暗示的,我需要创建一个随机的 17 个字符长的 ID。类似“ AJB53JHS232ERO0H1”的东西。字母和数字的顺序也是随机的。我想创建一个带有字母 AZ 的数组和一个随机到1-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.

But I feel like there is an easier way of doing this. Is there?

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

采纳答案by Suresh Atta

Here you can use my method for generating Random String

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

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;

    }

The above method from my bag using to generate a salt string for login purpose.

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

回答by cbt

RandomStringUtilsfrom Apache commons-lang might help:

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

RandomStringUtils.randomAlphanumeric(17).toUpperCase()


2017 update: RandomStringUtilshas been deprecated, you should now use RandomStringGenerator.

2017 更新RandomStringUtils已弃用,您现在应该使用RandomStringGenerator

回答by Masudul

You can easily do that with a for loop,

您可以使用 for 循环轻松做到这一点,

public static void main(String[] args) {
  String aToZ="ABCD.....1234"; // 36 letter.
  String randomStr=generateRandom(aToZ);

}

private static String generateRandom(String aToZ) {
    Random rand=new Random();
    StringBuilder res=new StringBuilder();
    for (int i = 0; i < 17; i++) {
       int randIndex=rand.nextInt(aToZ.length()); 
       res.append(aToZ.charAt(randIndex));            
    }
    return res.toString();
}

回答by MouseLearnJava

Three steps to implement your function:

实现功能的三个步骤:

Step#1You can specify a string, including the chars A-Z and 0-9.

步骤#1您可以指定一个字符串,包括字符 AZ 和 0-9。

Like.

喜欢。

 String candidateChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

Step#2Then if you would like to generate a random char from this candidate string. You can use

步骤#2然后,如果您想从这个候选字符串生成一个随机字符。您可以使用

 candidateChars.charAt(random.nextInt(candidateChars.length()));

Step#3At last, specify the length of random string to be generated (in your description, it is 17). Writer a for-loop and append the random chars generated in step#2 to StringBuilder object.

Step#3最后,指定要生成的随机字符串的长度(在您的描述中,它是17)。编写一个 for 循环并将步骤#2 中生成的随机字符附加到 StringBuilder 对象。

Based on this, here is an example public class RandomTest {

基于此,这里有一个示例 public class RandomTest {

public static void main(String[] args) {

    System.out.println(generateRandomChars(
            "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", 17));
}

/**
 * 
 * @param candidateChars
 *            the candidate chars
 * @param length
 *            the number of random chars to be generated
 * 
 * @return
 */
public static String generateRandomChars(String candidateChars, int length) {
    StringBuilder sb = new StringBuilder();
    Random random = new Random();
    for (int i = 0; i < length; i++) {
        sb.append(candidateChars.charAt(random.nextInt(candidateChars
                .length())));
    }

    return sb.toString();
}

}