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?

8 Years
Discussion Span
Last Post by Erikmmp

What I mean is, is there any way I could select a character from a string at random? for instance in python:
x = random.choice("Hello World")
and x would return of value of say "W" as an example.
Anyway at all to do this?
Thanks for your help.


Of course. I already mentioned you should use the rand() function. Lets say the string is "Hello World"

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.