码迷,mamicode.com
首页 > 其他好文 > 详细

字符串反转的3种方法

时间:2019-03-19 01:08:18      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:uil   source   bcd   使用   code   rev   ram   结果   word   

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;
}

字符串反转的3种方法

标签:uil   source   bcd   使用   code   rev   ram   结果   word   

原文地址:https://www.cnblogs.com/bk76120/p/10556037.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!