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?
You've got it. Just generate the random ASCII codes yourself. What do you need it for though?
Take a look at Java Randomizer class. I think you can randomize a character using the randomize(char[] array) method.
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:
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 generator based 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 generator in that case (e.g. java.security.SecureRandom
).
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.
You could use generators from the Quickcheck specification-based test framework.
To create a random string use anyString method.
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
}
}
To generate a random char in a-z:
Random r = new Random();
char c = (char)(r.nextInt(26) + 'a');
using dollar:
Iterable<Character> chars = $('a', 'z'); // 'a', 'b', c, d .. z
given chars
you can build a "shuffled" range of characters:
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:
public String randomString(int n) {
return $('a', 'z').shuffle().slice(n).toString();
}
NB: the condition n > 0
is cheched by 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
:
public String randomStringWithRepetitions(int n) {
return $('a', 'z').repeat(10).shuffle().slice(n).toString();
}
or just provide your alphabet as String
:
public String randomStringFromAlphabet(String alphabet, int n) {
return $(alphabet).shuffle().slice(n).toString();
}
String s = randomStringFromAlphabet("00001111", 4);
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.