Menu Close

C语言字符串练习题:用递归函数把一个字符串反转

程序设计了一个 reverse_string 函数

#include <stdio.h>
#include <string.h>
void reverse_string(char*, int, int);

int main()
{
    //This array would hold the string upto 150 char
    char string_array[150];
    printf("Enter any string:");
    scanf("%s", &string_array);

    //Calling our user defined function
    reverse_string(string_array, 0, strlen(string_array)-1);
    printf("\nReversed String is: %s",string_array);

    return 0;
}

void reverse_string(char *x, int start, int end)
{
    char ch;
    if (start >= end)
       return;

    ch = *(x+start);
    *(x+start) = *(x+end);
    *(x+end) = ch;

    //Function calling itself: Recursion
    reverse_string(x, ++start, --end);
}

results:

Enter any string:IamAgoodGuy

Reversed String is: yuGdoogAmaI
Process returned 0 (0x0) execution time : 22.758 s
Press any key to continue.

 

除教程外,本网站大部分文章来自互联网,如果有内容冒犯到你,请联系我们删除!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Leave the field below empty!

Posted in C语言习题集

Related Posts