RandomStringGenerator生成字母数字字符串
答
是,使用下面的代码:
import static org.apache.commons.text.CharacterPredicates.DIGITS;
import static org.apache.commons.text.CharacterPredicates.LETTERS;
// ...
RandomStringGenerator generator = new RandomStringGenerator.Builder()
.withinRange('0', 'z')
.filteredBy(LETTERS, DIGITS)
.build();
答
我用这个:
static char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'q', 'w', 'e', 'r', 't', 'z', 'u', 'i', 'o', 'p', 'a', 's',
'd', 'f', 'g', 'h', 'j', 'k', 'l', 'y', 'x', 'c', 'v', 'b', 'n', 'm', 'Q', 'W', 'E', 'R', 'T', 'Z', 'U', 'I', 'O', 'P', 'A',
'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Y', 'X', 'C', 'V', 'B', 'N', 'M' };
private static String randomString(int length) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < length; i++) {
stringBuilder.append(chars[new Random().nextInt(chars.length)]);
}
return stringBuilder.toString();
}
或
private static String randomString(int length) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < length; i++) {
switch (new Random().nextInt(3)) {
case 0:
stringBuilder.append((char) (new Random().nextInt(9) + 48));
break;
case 1:
stringBuilder.append((char) (new Random().nextInt(25) + 65));
break;
case 2:
stringBuilder.append((char) (new Random().nextInt(25) + 97));
break;
default:
break;
}
}
return stringBuilder.toString();
}
enter code here
+0
这还包括以下字符::; ?@ [\]^_' –
+0
@DavidRiccitelli是的,但现在正确。 – mate0406
答
与Java 8 Lambda表达式:
private final RandomStringGenerator generator = new RandomStringGenerator.Builder()
.usingRandom(max -> RandomUtils.getRandomAlphanumericChar()).build();
....................
public class RandomUtils {
private final static char[] ALPHA_NUMERIC_CHARS = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4',
'5', '6', '7', '8', '9'};
private final static Random random = new SecureRandom();
public static char getRandomAlphanumericChar() {
return ALPHA_NUMERIC_CHARS[random.nextInt(ALPHA_NUMERIC_CHARS.length)];
}
}
'LETTERS'和'DIGITS'从哪里来?它们是常量吗? –
'import static org.apache.commons.text.CharacterPredicates.DIGITS; import static org.apache.commons.text.CharacterPredicates.LETTERS;'。我更新了答案。 –
为什么不切断中间人,并使用'.filteredBy(Character :: isLetter,Character :: isDigit)'? – toKrause