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?

Recommended Answers

All 5 Replies

rand() returns a random value between 0 and MAX_RAND.

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.

Oh okay. Thanks a lot.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.