字符串反转

一、题目描述

写出一个程序,接受一个字符串,而后输出该字符串反转后的字符串。例如:
ios

输入描述:
spa

输入N个字符code

输出描述:
ci

输出该字符串反转后的字符串字符串

输入例子:get

abcd

输出例子:
input

dcba

二、程序

方案一

基本思路:循环输入,而后逆序循环输出。
string

#include <iostream>
#include <stdio.h>
#include <string>

using namespace std;

int main(){
    string str;
    getline(cin,str);
    //或者while(getline(cin,str))
    for(int i=str.length()-1;i>=0;i--){
    //或者for(i=str.length();i>0;i--)  
        cout<<str[i];
    }
    return 0;
}

方案二

基本思路:调用reverse()方法直接逆序输出。it

#include <iostream>
#include <string>
#include <algorithm>
 
using namespace std;
 
int main()
{
    string input;
    while (cin >> input)
    {
        reverse(input.begin(), input.end());
        cout << input << endl;
    }
 
    return 0;
}
相关文章
相关标签/搜索