C语言实现翻转字符串

2023-01-18 20:25:44

首先是用非递归的方法翻转字符串

#include<stdio.h>
#include<Windows.h>
#include<assert.h>

void swap(char *start, char *end)
{
	assert(start);
	assert(end);

	*start ^= *end;
	*end ^= *start;
	*start ^= *end;
}

void reverse_string(char str[], int len)
{
	assert(str);
	assert(len);

	char *start = str;
	char *end = str + len - 1;

	while (start < end)
	{
		swap(start, end);
		start++;
		end--;
	}

}


int main()
{
	char msg[] = "abcdef123456";

	printf("before:%s\n", msg);

	reverse_string(msg, strlen(msg));

	printf("after:%s\n", msg);

	system("pause");
	return 0;
}
递归实现翻转字符串,使程序更加简洁
#include<stdio.h>
#include<Windows.h>
#include<assert.h>

void reverse_string(char str[], int len)
{
	assert(str);

	if (*str == '\0')
	{
		return;
	}

	reverse_string(str + 1, len - 1);

	printf("%c", *str);

}

int main()
{
	char msg[] = "abcdef123456";

	reverse_string(msg, strlen(msg));

	system("pause");
	return 0;
}




  • 作者:Luella_G
  • 原文链接:https://blog.csdn.net/superficial_/article/details/52963447
    更新时间:2023-01-18 20:25:44