C函数strrev实现字符串反转

// 第一个与倒数一个个交换  第二个与倒数第二个交换 以此类推
//方法1:数组操作
void strrev1(const char* str,char* buffer)
{
	int len = strlen(str);

	strcpy(buffer,str);

	for (int i = 0; i < len / 2; ++i)
	{
		char c = buffer[i];         //字符串交换
		buffer[i] = buffer[len - i - 1];
		buffer[len - i - 1] = c;
	}
}

//方法2:指针交换或位交换
void strrev2(const char* str, char* buffer)
{
	strcpy(buffer, str);
	char* head = buffer;
	char* tail = buffer + strlen(buffer) - 1;

	while (tail > head)
	{
		char t = *head;
		*head = *tail;
		*tail = t;

		/*
		//位交换1
		*tail ^= *head;
		*head ^= *tail;
		*tail ^= *head;
		*/

		/*
		//位交换2
		*tail = *tail + *head;
		*head = *tail - *head;
		*tail = *tail - *head;
		*/

		--tail;
		++head;
	}
}

char* strrev3(char* str, int len)
{
	if (len <= 1)
		return str;

	char t = *str;
	*str = *(str + len - 1);
	*(str + len - 1) = t;

	// 最后的-1是为了让字符串的指针回到头部 若不减一 可自行外部打印传进来的str头指针

	return (strrev3(str + 1, len - 2) - 1);  
}


int main()
{
	char str[100] = "Welcome yoyou, my friend you";

//	strrev3(str,strlen(str));
//	cout << str << endl;

	cout << strrev3(str,strlen(str)) << endl;

	system("pause");
	return 0;
}
发布了55 篇原创文章 · 获赞 1 · 访问量 3795

猜你喜欢

转载自blog.csdn.net/lpl312905509/article/details/104083358