[c语言] 编写一个函数reverse_string(char * string)(递归实现)

2015-11-19 23:07:14 · 作者: · 浏览: 15
编写一个函数reverse_string(char * string)(递归实现)
?实现:将参数字符串中的字符反向排列。
要求:不能使用C函数库中的字符串操作函数。
?
#include 
#include 

int my_strlen(const char *str) //自定义的计算字符串长度的函数
{
    assert(str);
    int count = 0;
    while (*str)
    {
        count++;
        str++;
    }
    return count;
}

void reverse_string(char *str)//翻转字符串  将abcdef翻转为fedcba
{
    assert(str);
    char temp = 0;
    int len = my_strlen(str);
    if (len >
0) { temp = str[0]; str[0] = str[len - 1]; str[len - 1] = '\0'; //递归调用,限制条件len>0 ,每次调用的变化str++; reverse_string(str+1); str[len-1] = temp; } } int main() { char arr[] = "abcdef"; reverse_string(arr); printf("%s\n", arr); system("pause"); return 0; }

?