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