11

I am using String Builder from another answer, but I can't use anything but alpha/numeric, no whitespace, punctuation, etc. Can you explain how to limit the character set in this code? Also, how do I insure it is ALWAYS 30 characters long?

     Random generator = new Random();
    StringBuilder stringBuilder = new StringBuilder();
    int Length = 30;
    char tempChar ;
    for (int i = 0; i < Length; i++){
        tempChar = (char) (generator.nextInt(96) + 32);
        stringBuilder.append(tempChar);

I have looked at most of the other answers, and can't figure out a solution to this. Thanks. Don't yell at me if this is a duplicate. Most of the answers don't explain which part of the code controls how long the generated number is or where to adjust the character set.

I also tried stringBuilder.Replace(' ', '1'), which might have worked, but eclipse says there is no method for Replace for StringBuilder.

mavis
  • 3,100
  • 3
  • 24
  • 32
PrivusGuru
  • 273
  • 1
  • 2
  • 12
  • 1
    *"Most of the answers don't explain which part of the code controls how long the generated number is or where to adjust the character set."* ... pointing out the obvious is usually considered rude. – Brian Roach Aug 05 '13 at 23:31
  • I knew there would be people who would take umbrage with this question. Sorry if I offended, but the answers below have definitely added to the wealth and depth of knowledge available on the site. I do not think this is a duplicate, since the answers have more detailed explanations of the process. – PrivusGuru Aug 07 '13 at 15:42

3 Answers3

27

If you want to control the characterset and length take for example

public static String randomString(char[] characterSet, int length) {
    Random random = new SecureRandom();
    char[] result = new char[length];
    for (int i = 0; i < result.length; i++) {
        // picks a random index out of character set > random character
        int randomCharIndex = random.nextInt(characterSet.length);
        result[i] = characterSet[randomCharIndex];
    }
    return new String(result);
}

and combine with

char[] CHARSET_AZ_09 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();

to specify the characterset.

It's not based on StringBuilder since you know the length and don't need all the overhead.

It allocates a char[] array of the correct size, then fills each cell in that array with a randomly chosen character from the input array.

more example use here: http://ideone.com/xvIZcd

zapl
  • 63,179
  • 10
  • 123
  • 154
  • Thanks for ignoring the naysayers. This worked perfectly! – PrivusGuru Aug 07 '13 at 15:38
  • @PrivusGuru btw the code you posted generates numbers between `(0..95) + 32` => `32..127`. The characters that correspond to those numbers are here http://www.asciitable.com/ for example. Doing it the way your code does would mean limiting the random numbers to `48..57 OR 65..90 OR 97..122` which would be rather painful. (or you discard characters that are not in that range like e.g. @Sello proposed) – zapl Aug 07 '13 at 16:18
  • @zapl is it collision free? – Virtu Mar 28 '16 at 05:13
  • @Virtu No, it's random. That includes generating the same string 10 times in a row, although with very small probability. – zapl Mar 28 '16 at 06:16
2

Here's what I use:

public static String randomStringOfLength(int length) {
    StringBuffer buffer = new StringBuffer();
    while (buffer.length() < length) {
        buffer.append(uuidString());
    }

    //this part controls the length of the returned string
    return buffer.substring(0, length);  
}


private static String uuidString() {
    return UUID.randomUUID().toString().replaceAll("-", "");
}
aroth
  • 54,026
  • 20
  • 135
  • 176
0

You may try this:

    //piece
    int i = 0;
    while(i < length){
      char temp =(char) (generator.nextInt(92)+32);
      if(Character.isLetterOrDigit(temp))
      {
        stringBuilder.append(temp);
        ++i;
      }
    }
    System.out.println(stringBuilder);

Should achieve your goal

Sello
  • 297
  • 1
  • 8