C++反转字符串
- 互联网
- 2025-09-03 04:54:02

C++反转字符串 1、reverse()2、双指针方法3、字符串拼接 1、reverse() #include <algorithm> #include<bits/stdc++.h> using namespace std; int main(){ string s; cin >> s; reverse(s.begin(), s.end()); cout << s; return 0; } 2、双指针方法
思路:用两个指针从字符串的两端同时向中间移动,并在移动过程中交换字符的位置。
步骤: 1、输入字符串s 2、初始化指针:使用两个指针(或索引)i和j,分别指向字符串的开头(0)和结尾(s.size() - 1)。 3、交换字符: 1)在循环中,不断交换i和j所指向的字符,然后移动指针。i向右移动(i++),j向左移动(j–)。 2)循环继续,直到i和j相遇或i超过j。 4、输出反转后的字符串
#include<bits/stdc++.h> using namespace std; int main(){ string s; cin >> s; int i = 0, j = s.size() - 1; while(i < j){ swap(s[i++], s[j--]); } cout << s; return 0; } #include<bits/stdc++.h> using namespace std; int main(){ string s; cin >> s; int n = s.size(); for(int i = 0, j = n - 1; i < j; i++, j--){ swap(s[i], s[j]); } cout << s; return 0; } 3、字符串拼接通过遍历字符串并从头开始逐个字符添加到新字符串前,实现字符串的反转。
#include<bits/stdc++.h> using namespace std; string s1, s2; int main(){ cin >> s1; for(int i = 0; i < s1.size(); i++){ s2 = s1[i] + s2; } cout << s2; return 0; }