c++字符串反转

纵饮孤独 提交于 2019-12-08 06:35:07

第一种:使用string.h中的strrev函数

#include <iostream>
#include <cstring>
using namespace std;
 
int main()
{
    char s[]="hello";
 
    strrev(s);
 
    cout<<s<<endl;
 
    return 0;
}

第二种:使用algorithm中的reverse函数

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
 
int main()
{
    string s = "hello";
 
    reverse(s.begin(),s.end());
 
    cout<<s<<endl;
 
    return 0;
}

第三种:自己编写

 

#include <iostream>
using namespace std;
 
void Reverse(char *s,int n){
    for(int i=0,j=n-1;i<j;i++,j--){
        char c=s[i];
        s[i]=s[j];
        s[j]=c;
    }
}
 
int main()
{
    char s[]="hello";
 
    Reverse(s,5);
 
    cout<<s<<endl;
 
    return 0;
}

转自https://blog.csdn.net/szu_aker/article/details/52422191

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!