gpt4 book ai didi

java - 如何生成20个字符的随机字符串

转载 作者:IT老高 更新时间:2023-10-28 20:48:54 26 4
gpt4 key购买 nike

Possible Duplicate:
How to generate a random String in Java

我想在不使用 apache 类的情况下生成 20 个字符的随机字符串。我真的不在乎是否是字母数字。另外,我稍后会将其转换为字节数组。

谢谢,

最佳答案

给你。只需在第一行指定要允许的字符即可。

char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
StringBuilder sb = new StringBuilder(20);
Random random = new Random();
for (int i = 0; i < 20; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
String output = sb.toString();
System.out.println(output);

If you are using this to generate something sensitive like a password reset URL or session ID cookie or temporary password reset, be sure to use java.security.SecureRandom instead. Values produced by java.util.Random and java.util.concurrent.ThreadLocalRandom are mathematically predictable.

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com