SITERAW

Write a function that reverses a string in C

Author Message
Bougnoulz # Posted two hours ago
Bougnoulz

Hello everyone,

I'm new to coding and I'm struggling to write this function in C:

Write a function that reverses a string.

int main(void)
{
char s[19] = "Welcome to SiteRaw";

printf("%s\n", s);
rev_string(s);
printf("%s\n", s);
return (0);
}

Expected output:

Welcome to SiteRaw  
waRetiS ot emocleW

Could a kind soul please explain how to do this?

Thanks!

Ads
Phoenix # Posted two hours ago
Phoenix

It's pretty straightforward: using a loop, you swap the first character with the last, the second with the second-to-last, and so on... You stop once you reach the middle of the string, or you will end up just reversing it back to the original.

Storm # Posted one hour ago
Storm

That's from the tutorial quiz. You should try and figure it out yourself rather than asking for answers directly in the forum.

Kegon # Posted one hour ago
Kegon

Hi,

If you're allowed to use strlen(), use it to find the position of the last character. If not, you can loop through the string until you hit the '\0' to figure it out manually.

Then you use two indices — one that goes up from the start, and one that comes down from the end — and you swap the characters at those positions. You stop when the two indices meet (i.e., when the first one catches up to the second).

PS: It's totally okay to grab a pen and paper and sketch it out if that helps you picture how the algorithm works.

Clara # Posted 7 minutes ago
Clara

As others have said, you shouldn't ask for code directly, but rather for help with the logic (if you are stuck).

However I will give you some advice regarding the "reverse" function: it will probably need #include <string.h>. The rest is up to you.

Post a reply

Please be kind and courteous in your replies. Don't roast others for no reason.