944,123 Members | Top Members by Rank

Ad:
  • C Discussion Thread
  • Unsolved
  • Views: 10185
  • C RSS
Oct 28th, 2007
0

random string

Expand Post »
I have small question:
How can I create a random string from 'a' to 'z'?
thank you!
Similar Threads
Reputation Points: 10
Solved Threads: 0
Light Poster
donaldunca is offline Offline
27 posts
since Sep 2006
Oct 28th, 2007
0

Re: random string

Create a string containing all the letters you want to use. Seed and use rand() to access elements (using the % operator to force the numbers within the string's range). Strcat in a loop. Pseudo-code.

  1. my_letters = "abcdefghijklmnopqrstuvwxyz" /* allowable letters for your random string */
  2. my_random_string /* your random string. Initially empty */
  3.  
  4. srand( time(0) ) /* seed rand */
  5.  
  6. for i=0 to 10 /* or however long you want it */
  7. append( my_random_string, /* append to this string */
  8. my_letters[rand()%strlen(my_random_string)] ) /* this letter */
  9. end loop
Or something like that. Alternatively you could just rand() (limit up to 25) and add 'a' onto the number and append that to your string. I think the above method is better though because you can extend the characters you use (you could put numbers, symbols, capital letters in it). That is harder to do with the second method I mentioned.
Last edited by twomers; Oct 28th, 2007 at 8:12 am.
Reputation Points: 453
Solved Threads: 57
Posting Virtuoso
twomers is offline Offline
1,873 posts
since May 2007
Oct 28th, 2007
0

Re: random string

Use a loop to generate as many random numbers from 0 to 25 as you want and add the values to the string. When you get the random number, simply add 'a' to it and you will have all letters instead of 0-25
Moderator
Reputation Points: 3281
Solved Threads: 895
Posting Sage
WaltP is offline Offline
7,747 posts
since May 2006
Oct 30th, 2007
0

Re: random string

Thank you for your helps
Reputation Points: 10
Solved Threads: 0
Light Poster
donaldunca is offline Offline
27 posts
since Sep 2006

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C Forum Timeline: C program
Next Thread in C Forum Timeline: Problem when passing a structure containing an array of 2D-chars array to a function





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC