編寫一個函數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;
}