| | |
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 |
#include * adobe ansi api array asterisks binarysearch centimeter changingto char character cm copyimagefile cprogramme creafecopyofanytypeoffileinc createcopyoffile csyntax database directory dynamic feet fgets file fork frequency function getlasterror getlogicaldrivestrin givemetehcodez global grade graphics gtkgcurlcompiling gtkwinlinux hacking highest histogram include incrementoperators infiniteloop input interest kernel keyboard kilometer linked linkedlist linux linuxsegmentationfault list locate logical_drives looping loopinsideloop. lowest match matrix meter microsoft mqqueue mysql number odf opendocumentformat owf pattern pdf performance pointer posix probleminc process program programming radix recursion recv repetition research reversing scanf segmentationfault sequential shape single socket socketprograming standard string systemcall threads turboc unix user voidmain() wab whythiscodecausesegmentationfault windows.h windowsapi






