在 Java 中创建一个带有 A-Z 和 0-9 的随机字符串 [英] Creating a random string with A-Z and 0-9 in Java
本文介绍了在 Java 中创建一个带有 A-Z 和 0-9 的随机字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
正如标题所暗示的,我需要创建一个随机的、长度为 17 个字符的 ID.类似于AJB53JHS232ERO0H1
".字母和数字的顺序也是随机的.我想创建一个包含字母 A-Z 的数组和一个随机到 1-2
的检查"变量.并且在一个循环中;
As the title suggest I need to create a random, 17 characters long, ID. Something like "AJB53JHS232ERO0H1
". The order of letters and numbers is also random. I thought of creating an array with letters A-Z and a 'check' variable that randoms to 1-2
. And in a loop;
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.
但我觉得有一种更简单的方法可以做到这一点.有吗?
But I feel like there is an easier way of doing this. Is there?
推荐答案
这里可以使用我的方法生成随机字符串
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.
这篇关于在 Java 中创建一个带有 A-Z 和 0-9 的随机字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文