我正在尝试生成带有特殊字符的随机数
我对简单整数所做的是
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt();
我能做些什么才能在随机数字中得到这样的东西
String salt = "Random$SaltValue#WithSpecialCharacters12@$@4&#%^$*";
感谢
答案 0 :(得分:8)
您可以尝试以下操作:
代码:
final String alphabet = "<Your special characters>";
final int N = alphabet.length();
Random rd = new Random();
int iLength = <length you want>;
StringBuilder sb = new StringBuilder(iLength);
for (int i = 0; i < iLength; i++) {
sb.append(alphabet.charAt(rd.nextInt(N)));
}
答案 1 :(得分:7)
如果您乐意使用第三方库,您可能会发现Apache Commons Lang的RandomStringUtils
课程有用。
您可以指定允许的字符集(或使用所有可用字符)。
答案 2 :(得分:2)
import java.util.*;
class Test {
static Random r = new Random();
static char[] choices = ("abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"01234567890" +
"$#_").toCharArray();
public static String getSalt(int len) {
StringBuilder salt = new StringBuilder(len);
for (int i = 0; i<len; ++i)
salt.append(choices[r.nextInt(choices.length)]);
return salt.toString();
}
public static void main(String[]_) {
System.out.println(getSalt(32));
}
}
示例输出:vdq5L6bANFIQH_MUyKyZxLcOkJeB3uJ1
答案 3 :(得分:2)
如果您想生成此http://en.wikipedia.org/wiki/Special_characters个特殊字符,请尝试使用
char c = (char) (randomGenerator.nextInt(0xB4 - 21 + 1) + 21);
答案 4 :(得分:1)
String alphabet = "here specify all the characters you want";
final int N = alphabet.length();
Random r = new Random();
String finalStr= "";
for (int i = 0; i < 50; i++) {
finalStr+=alphabet.charAt(r.nextInt(N));
}