PTA 7-7 字符串逆序

7-7 字符串逆序 (20分)

输入一个字符串,对该字符串进行逆序,输出逆序后的字符串。

输入格式:
输入在一行中给出一个不超过80个字符长度的、以回车结束的非空字符串。

输出格式:
在一行中输出逆序后的字符串。

输入样例:

Hello World!

输出样例:

!dlroW olleH

思路:

  1. 偷个懒直接用reserve方法
  2. 直接逆序遍历输出字符串

代码 1:

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;
int main() {
    string a;
    getline(cin,a);
    reverse(a.begin(),a.end());
    cout<<a;
    return 0;
}

代码 2:

#include <iostream>
#include <string>
using namespace std;
int main() {
    string a;
    getline(cin,a);
    for(int i = a.length()-1; i >= 0 ; i--)
    {
    	cout<<a[i];
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_46039856/article/details/106459391