使用递归反转单词 [英] reverse a word using recursion

查看:65
本文介绍了使用递归反转单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 c 中的递归来反转一个单词,然后我做到了.

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

假设输入的字符串是我非常喜欢这个程序.该函数应该将字符串更改为 非常像 i

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"

我已经成功完成了第 1 步,但我不确定如何进一步进行.请帮忙.

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

推荐答案

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

这篇关于使用递归反转单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆