Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse words of string by recursion

I'm trying to write a C function that takes a string, and return a new string with reversed words. For example, entering "How are you" should return "you are How". The following is my trial:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *reverseWords(char *str, char *ac)
{
    if (!ac)
    {
        ac = malloc(strlen(str) + 1);
        ac[0] = '\0';
    }

    char *word = strtok(str, " ");
    if (!word)
    {
        return ac;
    }
    reverseWords(NULL, ac);
    strcat(ac, word);
    //strcat(ac, " ");
}

int main()
{
    char s[] = "How are you";
    char *reversed = reverseWords(s, NULL);
    printf("%s\n", reversed);
}

The previous code prints: "youareHow", so it seems that the idea is correct but just missing spaces. If I tried to uncomment the last line int the function, I don't get any output. so what's happening ? I can't understand why it didn't work.

like image 711
Youssef13 Avatar asked Aug 22 '26 07:08

Youssef13


1 Answers

You are neglecting the return value of reverseWords. I think this is ok because you have reference to ac

At the end of reverseWords function you are not returning ac which holds the contcatinated string.

Now you have to uncomment strcat(ac, " "); so that space will be added to the return value.

Now the return value will have the reversed string with spaces in it.

You forgot to free the allocated string.

like image 52
Shubham Avatar answered Aug 24 '26 22:08

Shubham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!