C++中STL的字符串反转
有时需要反转字符串的内容。假设要判断用户输入的字符串是否为回文,方法之一是将其反转,
再与原来的字符串进行比较。反转 STL string 很容易,只需使用泛型算法 std::reverse():
string sampleStr ("Hello String! We will reverse you!");
reverse (sampleStr.begin (), sampleStr.end ());
程序清单 16.6 演示了如何将算法 std::reverse()用于 std::string。
程序清单 16.6 使用 std::reverse 反转 STL string
0: #include <string>
1: #include <iostream>
2: #include <algorithm>
3:
4: int main ()
5: {
6: using namespace std;
7:
8: string sampleStr ("Hello String! We will reverse you!");
9: cout << "The original sample string is: " << endl;
10: cout << sampleStr << endl << endl;
11:
12: reverse (sampleStr.begin (), sampleStr.end ());
13:
14: cout << "After applying the std::reverse algorithm: " << endl;
15: cout << sampleStr << endl;
16:
17: return 0;
18: }
输出:
The original sample string is:
Hello String! We will reverse you!
After applying the std::reverse algorithm:
!uoy esrever lliw eW !gnirtS olleH
分析:
第 12 行的 std::reverse()算法根据两个输入参数指定的边界反转边界内的内容。在这里,两个边界
分别是 string 对象的开头和末尾,因此整个字符串都被反转。只要提供合适的输入参数,也可将字符
串的一部分反转。注意,边界不能超过 end()。
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string>
#include<algorithm>
#include<map>
#include<vector>
#include<queue>
using namespace std;
int main(){
string str="C++REVERSE";
reverse(&str[0],&str[3]);//注意翻转的是前三个字符,别漏了&
reverse(str.begin(),str.end());
cout<<str;
system("pause");
return 0;
}