在 Java 中用 A-Z 和0-9创建一个随机字符串

正如标题所示,我需要创建一个随机的,17个字符长,ID。像是“ AJB53JHS232ERO0H1”。字母和数字的顺序也是随机的。我想创建一个字母 A-Z 和一个随机到 1-2的‘ check’变量的数组。在一个循环里

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.

但我觉得有个更简单的办法,是吗?

265519 次浏览

RandomStringUtils from Apache commons-lang might help:

RandomStringUtils.randomAlphanumeric(17).toUpperCase()

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

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.

You can easily do that with a for loop,

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();
}

Three steps to implement your function:

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

Like.

 String candidateChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

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

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

Step#3 At 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.

Based on this, here is an example 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();
}


}