Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to reverse a word using recursion in c and i got upto this.

#include<stdio.h>

void reverse(char *a){
    if(*a){
        reverse(a+1);
        printf("%c",*a);
    }
}

int main() {
    char a[] = "i like this program very much";
    reverse(a); // i ekil siht margorp yrev 
    return 0;
}

Suppose the input string is i like this program very much. The function should change the string to much very program this like i

Algorithm:

1) Reverse the individual words, we get the below string.
     "i ekil siht margorp yrev hcum"
2) Reverse the whole string from start to end and you get the desired output.
     "much very program this like i"

I have successfully completed up-to step 1 and i am not sure how to proceed further. Please help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
140 views
Welcome To Ask or Share your Answers For Others

1 Answer

To help you out without giving too much away, I think your algorithm is too complicated. Instead of reversing individual words and then reversing the whole string, consider splitting the string into an array of strings with space as a delimiter. Then simply reverse the array.

The way to do this in C is a little bit odd; since you already use char arrays as strings, you actually need to make an array of char arrays. For example:

char a[] = "i like this program very much";

actually means

a = ['i', ' ', 'l', 'i', 'k', 'e', ' ', ... , 'c', 'h']

So, you want to create an array of char arrays so it now looks like this:

new_array = [['i'], ['l', 'i', 'k', 'e'], ... ['m', 'u', 'c', 'h']]

Then all you need to do is print the new array backwards, and you've got the output you want!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...