【问题标题】:Creating a random string with A-Z and 0-9 in Java [duplicate]在Java中创建一个带有A-Z和0-9的随机字符串[重复]
【发布时间】:2013-12-30 10:54:54
【问题描述】:

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

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

【问题讨论】:

标签: java random


【解决方案1】:

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

RandomStringUtils.randomAlphanumeric(17).toUpperCase()

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

【讨论】:

  • 考虑更新答案,因为 Apache 在 commons-text 中将其替换为 RandomStringGenerator
  • 你也可以使用RandomStringUtils.random(length, useLetters, useNumbers),其中length是int,而useLetters和useNumbers是boolean值。
  • 精湛,单行代码,我们需要这种类型的代码。
  • @NeriaNachum 您在哪里看到RandomStringUtils 已被替换/弃用?我只是看到“RandomStringUtils 适用于简单的用例。对于更高级的用例,请考虑改用 Apache Commons Text 的 RandomStringGenerator。” here
【解决方案2】:

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

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;

    }

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

【讨论】:

  • 我建议用StringBuilder 替换StringBuffer,不需要线程安全的实现。这里
  • 或者只是创建一个char[],因为您确切知道它将持续多长时间。无需附加任何东西。我也会使用Random.nextInt 而不是调用nextFloat 并将其乘以长度。
  • 请注意,数字的平均数量与字母的数量不同。
  • @RC。是的。我在 servlet 环境中使用它。所以需要它。否则为 StringBuilder
  • 如果你使用它要记住的一点是,Random 类是 sudo random 而不是真正的随机。试图用它来打印 400 个字符串到一个文件,发现它不像我想要的那样随机。 :(
【解决方案3】:

你可以通过 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();
}

【讨论】:

    【解决方案4】:

    实现你的功能的三个步骤:

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

    喜欢。

     String candidateChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    

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

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

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

    基于此,这里是一个例子 公共类 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();
    }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2014-11-22
      • 1970-01-01
      • 2019-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-08
      • 2013-06-16
      • 2014-10-03
      相关资源
      最近更新 更多