Search code examples
javarandomcardinality

Create a random string of a given cardinality


Is there a builtin (or otherwise trivial) method of generating a random string in Java given a certain given cardinality?

E.g.,, randStringCard(10,2) would create a random string of length 10 but with only two possible unique values

RandStringCard(1,26) would generate a single character with 26 values, and randStringCard(*,1) would always generate the same output.


Solution

  • This can be done by using Random and nextInt(<#differentChars>) to get an int in the range of different characters you want to support. Then you need to convert this number to a String and add it to the result, repeat "desiredLength" times.

    To convert the number to a String you could do as follows:

    if (n < 26)
      s += (char)('A' + n); // A-Z is used first
    else if (n < 36)
      s += n - 26; // then 0-9
    else
      s += ???; // symbols or lower case letters