tags:

views:

334

answers:

8

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?

A: 

You've got it. Just generate the random ASCII codes yourself. What do you need it for though?

Strelok
I have an algorithm that needs to generate random strings and apply them as "keys" to xor against other strings, as you would in a cryptographic function. This is what it will be used for
Chris
A: 

Take a look at Java Randomizer class. I think you can randomize a character using the randomize(char[] array) method.

manuel
@manuel, I think then we need to install the Liefra jar file, it doesnot come with the default one
harigm
+6  A: 

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).

polygenelubricants
Nice and simple.
Sheldon
Concise? Yes. Clever? Yes. Simple? For a Java novice, probably not.
Stephen C
A: 
   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.

ring bearer
This is most likely not what was intended, because in that range you include a whole number of control characters which are very unlikely to be expected.
Joachim Sauer
A: 

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
  }
}
Thomas Jung
+1  A: 

To generate a random char in a-z:

Random r = new Random();
char c = (char)(r.nextInt(26) + 'a');
dogbane
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);
dfa
This will use each character at most once in the random string. This may not be what the OP needs.
Steve McLeod
@Steve: thanks, I've fixed my answer and extended the library http://bitbucket.org/dfa/dollar/changeset/4c26ccf9464e/
dfa
A: 
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.

Peter Walser