java - 在java中生成随机字符串

标签 java string random secure-random

<分区>

我正在尝试使用 Secure Random 在 Java 中生成大写字母 A-Z 之间的字符串。目前我能够生成一个包含特殊字符的字母数字字符串,但我想要一个仅包含大写字母的字符串。

  public String createRandomCode(int codeLength, String id){   
     char[] chars = id.toCharArray();
        StringBuilder sb = new StringBuilder();
        Random random = new SecureRandom();
        for (int i = 0; i < codeLength; i++) {
            char c = chars[random.nextInt(chars.length)];
            sb.append(c);
        }
        String output = sb.toString();
        System.out.println(output);
        return output ;
    } 

输入参数是输出字符串的长度和 id whhich 是字母数字字符串。无法理解对上述代码进行哪些修改以仅生成大写字母字符串。请帮助..

最佳答案

您的方法从 id 参数中随机选择字符。如果您希望它们只是大写字母,则传递包含这些字符的字符串:

String randomCode = createRandomCode(length, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");

编辑 如果您想避免重复,您不能只是随机选择字符。您需要将它们打乱顺序并挑选出前 n 个字符:

public String createRandomCode(int codeLength, String id) {   
    List<Character> temp = id.chars()
            .mapToObj(i -> (char)i)
            .collect(Collectors.toList());
    Collections.shuffle(temp, new SecureRandom());
    return temp.stream()
            .map(Object::toString)
            .limit(codeLength)
            .collect(Collectors.joining());
}

EDIT 2 为了好玩,这是实现原始随机代码生成器的另一种方法(允许重复):

public static String createRandomCode(int codeLength, String id) {
    return new SecureRandom()
            .ints(codeLength, 0, id.length())
            .mapToObj(id::charAt)
            .map(Object::toString)
            .collect(Collectors.joining());
}

关于java - 在java中生成随机字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39222044/

相关文章:

javascript - 字符串中包含的以 10 为基数的大数字的最佳压缩

java - 随机化字符串数组,但不重复元素

java - 部署到 war 的 Spring Boot 不发送谷歌电子邮件

java - 为什么 Java InetAddress.isReachable() 不能像在 JRE 1.7.x 上那样在 JRE 1.8.x 上工作

r - 使用因子将 ggplot 中的标签拆分为 2 行

java - 生成一个大于或小于前一个随机数的随机数

postgresql - postgres随机使用setseed

java - 如何分组并删除重复的对象

Java程序设计-洗牌器

string - C++/CX : Why doesn't returning a StringReference work like passing one as an argument?