字符串反转的3种方法

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

猜你喜欢

转载自www.cnblogs.com/bk76120/p/10556037.html
今日推荐