c++内置函数实现字符串翻转(reverse,strrev,string 构造函数)
·
c++内置函数实现字符串翻转(reverse,strrev,string 构造函数)
在写程序的时候,我们经常需要将字符串进行翻转。c++中内置的函数有不少个可以实现该功能。
1.strrev函数。(cstring)
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string s="abcd";
strrev(s);
cout<<s<<endl;
return 0;
}
一般算法题中不能使用,因为不包含cstring。
2.reverse函数(algorithm)
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string s = "abcd";
reverse(s.begin(),s.end());
cout<<s<<endl;
return 0;
}
一般算法题中基本能用,偶尔不能用。因为有些题解不让使用algorithm。空间消耗小。
3.利用string构造函数(string)
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string s = "hello";
cout<<string(s.rbegin(),s.rend())<<endl;//通过string构造函数,传入原字符串的逆向迭代器。
return 0;
}
一般都可以用。空间消耗大。
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐



所有评论(0)