Generating an alphanumeric random string in Java

I am using String Builder from another answer, but I cannot use anything other than alpha / numeric, without spaces, punctuation, etc. Can you explain how to limit the character set in this code? Also, how can I guarantee that it ALWAYS lasts 30 characters?

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 went through most of the other answers and cannot find a solution to this. Thank you Do not yell at me if this is a duplicate. Most answers do not explain how much of the code determines how long the generated number is or where you can configure the character set.

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

+8
java string random alphanumeric
source share
3 answers

If you want to control the character set and length, 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 a character set.

It is not based on StringBuilder , since you know the length and do not need all the overhead.

It selects the char[] array of the correct size, then fills each cell in this array with a randomly selected character from the input array.

more examples are used here: http://ideone.com/xvIZcd

+21
source share

Here is 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("-", ""); } 
+2
source share

You can try the following:

  //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); 

Reach your goal

0
source share

All Articles