第一种方法:
using namespace std; void Reverse(string &a) { int n = a.size(); char b; for(int i=0;i<n/2;i++) //通过第1个字符和第n个字符交换位置,第二个和第n-1个交换…实现该功能 { b = a[i]; a[i] = a[n-1-i]; a[n-i-1] = b; } } int main() { string a; getline(cin,a); cout << "a=" << a <<endl; Reverse(a); cout << "a=" << a <<endl; return 0; }
第二种方法:
#include <iostream> #include <string.h> using namespace std; void Reverse(string &a,string &b) { int n = a.size(); b.resize(n); for(int i=0;i<n;i++) { b[i] = a[n-1-i]; //通过a的倒序遍历赋值给b } } int main() { string a; string b; getline(cin,a); cout << "a=" << a <<endl; Reverse(a,b); cout << "b=" << b <<endl; return 0; }