欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

三种方法reverse字符串

程序员文章站 2022-03-22 08:10:46
...

1.自己编写函数,不调用库函数

首先当然是自己写函数实现啦,不调用库函数来反转

#include <iostream>
#include <string>
using namespace std;
void reverse(string& s ,int n){
    char c;
    for(int i=0,j=n-1;i<j;i++,j--){
        c=s[i];
        s[i]=s[j];
        s[j]=c;
        }
}
int main(){
    string str;
    getline(cin,str);
    reverse(str,str.length());
    cout<<str<<endl;
}

 2.调用algorithm模块中的reverse函数

学习stl非常重要,学习C++的必备,侯俊杰老师的《STL源码剖析》可以看看!!!

这里借助的是stl里面的algorithm模块,实现对容器的反转函数reverse(iterator * begin, iterator *end),直接作用于容器。

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

3.调用strrev()函数

注意strrev()函数只是对字符数组有效,但是对string无效

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

据说该函数位于string.h文件,但是我的ubuntu下gcc编译器说没有它。

详细看Stack Overflow的解说,有人说已经没有该函数了。链接:https://*.com/questions/8534274/is-the-strrev-function-not-available-in-linux

--------------------------------------------------------------后续有新方法会继续更新

相关标签: reverse