| | |
Random Choice
![]() |
Hi I'm pretty new to C (about a week experience) and I was wondering if C had anything like Python's random.choice() function. Basically it just selected a random element from what you gave it, a number from an array or a character from a string. If there is no function for this, if anyone could suggest a way around it, so for instance, I have a string "Hello World", how could I pull a random character out of that?
Of course. I already mentioned you should use the rand() function. Lets say the string is "Hello World"
The above is a little long winded, but illustrates how to do it.
C Syntax (Toggle Plain Text)
char str[] = "Hello World"; int len = strlen(str); // length of the string int x = rand() % len; // get a number between 0 and length of string char c = str[x]; // get the character
The above is a little long winded, but illustrates how to do it.
Last edited by Ancient Dragon; Dec 1st, 2008 at 7:06 pm.
Don't PM me with questions -- you might get a nasty PM in response. If you have a question then post it in one of the forums.
![]() |
Similar Threads
- VB 6.0. Creating a file for random access (Visual Basic 4 / 5 / 6)
- Random.randrange & counting (Python)
- Python noob needs random help (Python)
- regarding the random generated (Java)
- Function that creates random changes in a string?? (Python)
Other Threads in the C Forum
- Previous Thread: Arrays and Pointers
- Next Thread: Calculate text bounding box size in pixels
| Thread Tools | Search this Thread |
adobe ansi api array asterisks binarysearch calculate centimeter changingto char convert copyanyfile copyimagefile copypdffile cprogramme creafecopyofanytypeoffileinc createcopyoffile createprocess() csyntax database directory fflush file fork forloop frequency givemetehcodez global grade gtkgcurlcompiling hacking highest histogram homework i/o inches infiniteloop input interest iso kernel kilometer km linked linkedlist linux linuxsegmentationfault list locate looping loopinsideloop. lowest match meter microsoft mysql number open opendocumentformat owf pattern pdf performance posix power probleminc process program programming pyramidusingturboccodes radix read recv repetition research reversing scanf scheduling segmentationfault send sequential single socket socketprograming socketprogramming stack standard string suggestions systemcall threads turboc unix user variable voidmain() wab win32api windows.h windowsapi






