Generate Random String

Put your problem here if it does not fit any of the other categories.

Generate Random String

Postby suhasmannar » Fri Nov 12, 2010 6:03 am

Hi,

I have a string that contains 'n' number of values. I need to select a random value each time and print it.
How do i generate a random value.
suhasmannar
Developer
Developer
 
Posts: 28
Joined: Thu May 06, 2010 6:27 am
Location: Karnataka, India

Top

Re: Generate Random String

Postby urbantrad » Fri Nov 12, 2010 1:34 pm

Code: Select all
char[] chars = new char[] {'a', 'b', 'c', .... , 'z'};
String result = "";
for (int i = 0; i<n; i++)
     result += chars.get(Math.random()*26);

is something like that what you're looking for? Initializing the array like this is a lot of work though, i'm sure there must be better ways to it.
urbantrad
Senior Developer
Senior Developer
 
Posts: 104
Joined: Thu Sep 09, 2010 10:19 pm

Re: Generate Random String

Postby jonbonazza » Mon Nov 15, 2010 7:22 pm

How is your "string" stored? As a string, a character array, a string array, or a vector?
jonbonazza
Master Developer
Master Developer
 
Posts: 665
Joined: Thu Jul 15, 2010 2:58 pm
Location: WV USA

Re: Generate Random String

Postby Fsmv » Mon Nov 15, 2010 10:12 pm

You can convert decimal values into ascii the values I assume you want are 33-126 you may consult asciitable.com if you want a different set. To conver decimal to ascii you need to do:
Code: Select all
int random = Math.random()*(126-33);
char temp = (char) (random + 33);
String str += Character.toString(temp);

Then put that in a for loop .
Fsmv
Freshman
Freshman
 
Posts: 3
Joined: Mon Nov 15, 2010 9:39 pm

Top

Return to Other Coding-Problems

Who is online

Users browsing this forum: No registered users and 13 guests