(C语言)函数递归实现将参数字符串中的字符反向排列(要求:不能使用C函数库中的字符串操作函数)

函数递归实现将参数字符串中的字符反向排列(要求:不能使用C函数库中的字符串操作函数)

则原数组内存的是 “abcdefg\0”
调用函数:先将字符 a 入栈保存起来(如下图),将 g 赋给 a ,再将 g 赋为"\0"(字符串变为gbcdef\0),

a

调用函数:指针后移一个位置,(->gbcdef\0变为g->bcdef\0)传给函数的参数字符串变为"bcdef\0"
再将字符 b 入栈保存起来(如下图),将 f 赋给 b,再将原 f 赋为"\0"(字符串变为gfcde\0)

b
a

调用函数:指针再后移一个位置,(g->fcde\0变为gf->cde\0)传给函数的参数字符串变为"cde\0"
再将字符 c入栈保存起来(如下图),将e 赋给 c,再将原 e 赋为"\0"(字符串变为gfed\0)

c
b
a

调用函数:指针再后移一个位置,(gf->ed\0变为gfe->d\0)传给函数的参数字符串变为"d\0"
然后 ,参数字符串"d\0"长度 - 1=0,不符合条件,不再执行,结束此次函数调用
退出一次函数调用,将保存在栈顶的c放到"\0"的位置,参数字符串变为"edc\0"e
退出一次函数调用,再将保存在栈中间的b放到"\0"的位置,参数字符串变为"fedcb\0"
退出一次函数调用,再将保存在栈底a放到"\0"的位置,参数字符串变为"gfedcba\0"

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void reverse_string(char * string) {
	int len = strlen(string) - 1;
	char tmp;
	if (len > 0) {
		tmp = *string;
		*string = *(string + len);
		*(string + len) = '\0';
		reverse_string(string + 1);
		*(string + len) = tmp;
	}
}
void main() {
	char str[] = { "abcdefg" };
	printf("原字符串为:%s\n", str);
	reverse_string(str);
	printf("转换后字符串为:%s\n", str);
	system("pause");
}

运行结果如下:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_41071068/article/details/89163227