是否有在 Java 中生成随机字符的功能?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2626835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there functionality to generate a random character in Java?
提问by Chris
Does Java have any functionality to generate random characters or strings? Or must one simply pick a random integer and convert that integer's ascii code to a character?
Java 是否具有生成随机字符或字符串的功能?还是必须简单地选择一个随机整数并将该整数的 ascii 代码转换为一个字符?
采纳答案by polygenelubricants
There are many ways to do this, but yes, it involves generating a random int
(using e.g. java.util.Random.nextInt
) and then using that to map to a char
. If you have a specific alphabet, then something like this is nifty:
有很多方法可以做到这一点,但是是的,它涉及生成一个随机数int
(使用 eg java.util.Random.nextInt
),然后使用它来映射到char
. 如果你有一个特定的字母表,那么像这样的东西很漂亮:
import java.util.Random;
//...
Random r = new Random();
String alphabet = "123xyz";
for (int i = 0; i < 50; i++) {
System.out.println(alphabet.charAt(r.nextInt(alphabet.length())));
} // prints 50 random characters from alphabet
Do note that java.util.Random
is actually a pseudo-random number generatorbased on the rather weak linear congruence formula. You mentioned the need for cryptography; you may want to investigate the use of a much stronger cryptographically secure pseudorandom number generatorin that case (e.g. java.security.SecureRandom
).
请注意,java.util.Random
它实际上是一个基于相当弱的线性同余公式的伪随机数生成器。你提到了密码学的必要性;在这种情况下(例如),您可能想要研究使用更强大的加密安全伪随机数生成器。java.security.SecureRandom
回答by manuel
Take a look at Java Randomizerclass. I think you can randomize a character using the randomize(char[] array) method.
看看 Java Randomizer类。我认为您可以使用 randomize(char[] array) 方法随机化一个字符。
回答by ring bearer
Random randomGenerator = new Random();
int i = randomGenerator.nextInt(256);
System.out.println((char)i);
Should take care of what you want, assuming you consider '0,'1','2'.. as characters.
应该照顾你想要的,假设你认为 '0,'1','2'.. 作为字符。
回答by Thomas Jung
You could use generators from the Quickcheck specification-based test framework.
您可以使用Quickcheck 基于规范的测试框架中的生成器。
To create a random string use anyStringmethod.
要创建随机字符串,请使用anyString方法。
String x = anyString();
You could create strings from a more restricted set of characters or with min/max size restrictions.
您可以从更受限制的字符集或具有最小/最大大小限制的字符集创建字符串。
Normally you would run tests with multiple values:
通常,您会使用多个值运行测试:
@Test
public void myTest() {
for (List<Integer> any : someLists(integers())) {
//A test executed with integer lists
}
}
回答by dogbane
To generate a random char in a-z:
在 az 中生成一个随机字符:
Random r = new Random();
char c = (char)(r.nextInt(26) + 'a');
回答by dfa
using dollar:
使用美元:
Iterable<Character> chars = $('a', 'z'); // 'a', 'b', c, d .. z
given chars
you can build a "shuffled" range of characters:
鉴于chars
您可以构建一个“混洗”的字符范围:
Iterable<Character> shuffledChars = $('a', 'z').shuffle();
then taking the first n
chars, you get a random string of length n
. The final code is simply:
然后取第一个n
字符,你会得到一个长度为随机的字符串n
。最后的代码很简单:
public String randomString(int n) {
return $('a', 'z').shuffle().slice(n).toString();
}
NB: the condition n > 0
is cheched by slice
注意:条件n > 0
由slice
EDIT
编辑
as Steve correctly pointed out, randomString
uses at most once each letter. As workaround
you can repeat the alphabet m
times before call shuffle
:
正如史蒂夫正确指出的那样,randomString
每个字母最多使用一次。作为解决方法,您可以m
在通话前重复字母时间shuffle
:
public String randomStringWithRepetitions(int n) {
return $('a', 'z').repeat(10).shuffle().slice(n).toString();
}
or just provide your alphabet as String
:
或者只是提供您的字母表String
:
public String randomStringFromAlphabet(String alphabet, int n) {
return $(alphabet).shuffle().slice(n).toString();
}
String s = randomStringFromAlphabet("00001111", 4);
回答by Peter Walser
private static char rndChar () {
int rnd = (int) (Math.random() * 52); // or use Random or whatever
char base = (rnd < 26) ? 'A' : 'a';
return (char) (base + rnd % 26);
}
Generates values in the ranges a-z, A-Z.
生成 az、AZ 范围内的值。
回答by Josema
You could also use the RandomStringUtils from the Apache Commons project:
您还可以使用 Apache Commons 项目中的 RandomStringUtils:
Dependency:
依赖:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
Usages:
用法:
RandomStringUtils.randomAlphabetic(stringLength);
RandomStringUtils.randomAlphanumeric(stringLength);
回答by duggu
In following 97 ascii value of small "a".
在下面的 97 位 ascii 值中小“a”。
public static char randomSeriesForThreeCharacter() {
Random r = new Random();
char random_3_Char = (char) (97 + r.nextInt(3));
return random_3_Char;
}
in above 3 number for a , b , c or d and if u want all character like a to z then you replace 3 number to 25.
在 a , b , c 或 d 上面的 3 个数字中,如果你想要 a 到 z 之类的所有字符,那么你将 3 个数字替换为 25。
回答by schnatterer
polygenelubricants' answeris also a good solution if you only want to generate Hex values:
如果您只想生成十六进制值,polygenelubricants 的答案也是一个很好的解决方案:
/** A list of all valid hexadecimal characters. */
private static char[] HEX_VALUES = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'A', 'B', 'C', 'D', 'E', 'F' };
/** Random number generator to be used to create random chars. */
private static Random RANDOM = new SecureRandom();
/**
* Creates a number of random hexadecimal characters.
*
* @param nValues the amount of characters to generate
*
* @return an array containing <code>nValues</code> hex chars
*/
public static char[] createRandomHexValues(int nValues) {
char[] ret = new char[nValues];
for (int i = 0; i < nValues; i++) {
ret[i] = HEX_VALUES[RANDOM.nextInt(HEX_VALUES.length)];
}
return ret;
}