生成仅包含指定字符的指定长度的随机字符串(在 Java 中) [英] Generate a random string of specified length that contains only specified characters (in Java)
本文介绍了生成仅包含指定字符的指定长度的随机字符串(在 Java 中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有谁知道在Java中生成指定长度和字符的随机字符串的好方法.
Does anybody know of a good way to generate a random String of specified length and characters in Java.
例如,'length' 可以是 5,'possibleChars' 可以是 'a,b,c,1,2,3,!'.
For example 'length' could be 5 and 'possibleChars' could be 'a,b,c,1,2,3,!'.
所以
c!a1b 有效
但是
cba16 不是.
我可以尝试从头开始写一些东西,但我觉得这一定是生成密码、生成优惠券代码等事情的常见用例......
I could try to write something from scratch but I feel like this must be a common use case for things like generating passwords, generating coupon codes, etc...
有什么想法吗?
推荐答案
你想要这样的东西吗?
Random r=new Random();
char[] possibleChars="abc123!".toCharArray();
int length=5;
char[] newPassword=new char[length];
for (int i=0; i<length;i++)
newPassword[i]=possibleChars[r.nextInt(possibleChars.length)];
System.out.println(new String(newPassword));
这篇关于生成仅包含指定字符的指定长度的随机字符串(在 Java 中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文