How do I create a random String?
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   josh_knowles
Posted On:   Tuesday, April 10, 2001 02:19 PM

How would I go about creating a random string containing upper/lower case characters and/or numbers that is n characters long.

Thanks,

~josh

Re: How do I create a random String?

Posted By:   AlessandroA_Garbagnati  
Posted On:   Tuesday, April 10, 2001 03:33 PM

Hi,

If you need JUST upper/lower case characters and/or numbers, but you do not want all the characters that are in the ASCII table between numbers, upper case letters and lower case (ie: ^ ` = and so on), you can use this other solution:

private final static String CHAR_LIST = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXWZabcdefghijklmnopqrstuvwxyz";
int strSize = 16;
StringBuffer rndStr = new StringBuffer();
for (int i=0; i rndStr.append(CHAR_LIST.charAt(random.nextInt(CHAR_LIST.length())));
}
System.out.println("-> " + rndStr.toString());

In this case, you can put in the static variable CHAR_LIST only the characters that you would like to use.

Re: How do I create a random String?

Posted By:   Michael_Wax  
Posted On:   Tuesday, April 10, 2001 03:10 PM

Here is one way, which gives you a random string of upper case letters. Adusting the bottom and range values will give you different characters.

int stringSize = 16;
int bottom = 64;
int range = 26;
char[] randomChars = new char[8];
for (int i = 0; i < stringSize; i++) {
randomChars[i] = (char) (bottom + random.nextInt(range));
}
String randomString = new String(randomChars);
About | Sitemap | Contact