我试图在c中使用递归来反转单词,但我对此有所了解。

#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;
}


假设输入字符串是i like this program very much。该函数应将字符串更改为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"


我已成功完成第1步,但不确定如何继续进行。请帮忙。

最佳答案

#include <stdio.h>
#include <ctype.h>

void swap(char *a, char *b){
    char wk = *a;
    *a = *b;
    *b = wk;
}

void strpartrev(char *top, char *tail){
    while(top < tail)
        swap(top++, tail--);
}

void step1(char *a){
    while(isspace(*a))
        ++a;
    if(!*a)
        return;
    char *top =a;
    while(a[1] && !isspace(a[1]))
        ++a;
    char *tail = a;
    strpartrev(top, tail);
    step1(a+1);
}

int step2(char *str, int pos){
    char ch = str[pos];
    return (ch == '\0')? 0 : ((str[pos=step2(str, ++pos)]=ch), ++pos);
}

void reverse(char *a){
    step1(a);
    step2(a, 0);
}

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

关于c - 使用递归反转单词,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25164344/

10-10 03:51