我一直在寻找一种简单的Java算法来生成伪随机字母数字字符串。在我的情况下,它将被用作唯一的会话/密钥标识符,“很可能”在超过50万代的时间内是唯一的(我的需求实际上不需要更复杂的东西)。
理想情况下,我可以根据我的独特性需求指定长度。例如,生成的长度为12的字符串可能看起来像“AEYGF7K0DM1X”。
我一直在寻找一种简单的Java算法来生成伪随机字母数字字符串。在我的情况下,它将被用作唯一的会话/密钥标识符,“很可能”在超过50万代的时间内是唯一的(我的需求实际上不需要更复杂的东西)。
理想情况下,我可以根据我的独特性需求指定长度。例如,生成的长度为12的字符串可能看起来像“AEYGF7K0DM1X”。
当前回答
在前面的答案中有很多StringBuilder的用法。我想这很简单,但它需要每个字符调用一个函数,增加一个数组,等等。。。
如果使用字符串生成器,建议指定字符串所需的容量,即。,
new StringBuilder(int capacity);
这是一个不使用StringBuilder或字符串附加的版本,也没有字典。
public static String randomString(int length)
{
SecureRandom random = new SecureRandom();
char[] chars = new char[length];
for(int i=0; i<chars.length; i++)
{
int v = random.nextInt(10 + 26 + 26);
char c;
if (v < 10)
{
c = (char)('0' + v);
}
else if (v < 36)
{
c = (char)('a' - 10 + v);
}
else
{
c = (char)('A' - 36 + v);
}
chars[i] = c;
}
return new String(chars);
}
其他回答
使用Apache Commons库,可以在一行中完成:
import org.apache.commons.lang.RandomStringUtils;
RandomStringUtils.randomAlphanumeric(64);
文档
根据您的要求更改字符串字符。字符串是不可变的。这里StringBuilder.append比字符串串联更有效。
public static String getRandomString(int length) {
final String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+";
StringBuilder result = new StringBuilder();
while(length > 0) {
Random rand = new Random();
result.append(characters.charAt(rand.nextInt(characters.length())));
length--;
}
return result.toString();
}
我正在使用Apache Commons的库生成一个字母数字字符串:
import org.apache.commons.lang3.RandomStringUtils;
String keyLength = 20;
RandomStringUtils.randomAlphanumeric(keylength);
它又快又简单!
public static String RandomAlphanum(int length)
{
String charstring = "abcdefghijklmnopqrstuvwxyz0123456789";
String randalphanum = "";
double randroll;
String randchar;
for (double i = 0; i < length; i++)
{
randroll = Math.random();
randchar = "";
for (int j = 1; j <= 35; j++)
{
if (randroll <= (1.0 / 36.0 * j))
{
randchar = Character.toString(charstring.charAt(j - 1));
break;
}
}
randalphanum += randchar;
}
return randalphanum;
}
我使用Math.random()使用了一个非常原始的算法。为了增加随机性,可以直接实现util.Date类。尽管如此,它还是有效的。
一个简单的解决方案,但它只使用小写和数字:
Random r = new java.util.Random ();
String s = Long.toString (r.nextLong () & Long.MAX_VALUE, 36);
大小约为12位数,以36为基数,这样就无法进一步改进。当然,您可以附加多个实例。