Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

c - reverse a word using recursion

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

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

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...