C/C++字符串反转的N种方法

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;
}
posted @ 2019-03-18 23:36  iZero  阅读(4434)  评论(0编辑  收藏  举报