欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

字符串反转的3种方法

程序员文章站 2022-08-27 11:02:31
0x00 自己写一个 0x01 使用strrev函数 0x02 使用algorithm中的reverse ......

0x00 自己写一个

// 第一种
std::string reverse(std::string str)
{
	std::string res("");
	for (int i = str.size() - 1; i >= 0; i--)
	{
		res += str[i];
	}
	return res;
}
// 第二种
int main(void)
{
	std::string str("abcde");
	int i = 0, j = str.size() - 1;
	while (i < j)
	{
		// 交换
		str[i] = str[j] ^ str[i];
		str[j] = str[j] ^ str[i];
		str[i] = str[j] ^ str[i];
		j--;
		i++;
	}
	std::cout << str.c_str() << std::endl;
	return 0;
}

0x01 使用strrev函数

int main(void)
{
	char s[] = "abcde";
	strrev(s);
	std::cout << s << std::endl;
	return 0;
}
// 结果:edcba

0x02 使用algorithm中的reverse

#include <algorithm>
int main(void)
{
	std::string str("abcde");
	reverse(str.begin(),str.end());
	std::cout << str.c_str() << std::endl;
	return 0;
}