编写一个函数reverse_string(char * string)(递归实现)
实现:将参数字符串中的字符反向排列。
要求:不能使用C函数库中的字符串操作函数。
#include <stdio.h> #include <assert.h> 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; }
reverse_string()函数的递归调用具体情况如下图:
本文出自 “娜些维度的雪” 博客,请务必保留此出处http://1536262434.blog.51cto.com/10731069/1711558
【c语言】 编写一个函数reverse_string(char * string)(递归实现)
原文:http://1536262434.blog.51cto.com/10731069/1711558