反转字符串(杂谈)

反转字符串是个很简单也比较经常使用的方法ios

此随笔仅作杂谈,无技术含量spa

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <string>
 4 using namespace std;
 5 
 6 void myReverse(const string& str) {
 7     char* c_str = (char*)str.c_str();
 8     char* p, * q;
 9     p = c_str;
10     q = c_str + str.size() - 1;
11     while (p < q) {
12         char temp_c = *p;
13         *p = *q;
14         *q = temp_c;
15         p++;
16         q--;
17     }
18 }
19 
20 int main() {
21     string str = "123456789";
22     myReverse(str);    // 反转方式1
23     cout << str << endl;
24     reverse(str.begin() + 2, str.end() - 2);    // 反转方式2
25     cout << str << endl;
26     cout << string(str.rbegin(), str.rend());    // 反转方式3
27     return 0;
28 }

 

运用迭代器还有更多有趣的写法code

这里不一一列出blog

相关文章
相关标签/搜索