字符串反转

1、题目描述

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

输入描述:

输入N个字符

输出描述:

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

输入例子:

abcd

输出例子:

dcba

2、程序

方案一

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

#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()方法直接逆序输出。

#include <iostream>
#include <string>
#include <algorithm>
 
using namespace std;
 
int main()
{
    string input;
    while (getline(cin,input))
    {
        reverse(input.begin(), input.end());
        cout << input << endl;
    }
 
    return 0;
}
注意:一定要记得添加命名空间using namespace std,否则会报错,如果不添加那么每个函数之前应该加上std:
#include <iostream>
#include <string>
#include <algorithm>
 
//using namespace std;
 
int main()
{
    std::string input;
    while (getline(std::cin,input))
    {
        reverse(input.begin(), input.end());
        std::cout << input << std::endl;
    }
 
    return 0;
}
 
 
posted @   程序员姜戈  阅读(188)  评论(0编辑  收藏  举报
编辑推荐:
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
阅读排行:
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!
点击右上角即可分享
微信分享提示