C++中字符串反转的方法

在python中有切片的方法可以很方便的对矩阵、队列等完成截取,反转等操作,但在C++中没有类似的函数。现在列举一下常用的字符串反转的方法。

第一种:使用C语言中的strrev函数,但是该函数只能对char*类型进行操作,不能作用与string对象。

#include <iostream>
#include <string.h>
using namespace std;

int main()
{
    char ctype_str = "hello world";
    strrev(ctype_str);

    cout << ctype_str;  //"dlrow olleh"
    return 0;
}

第二种:使用头文件<algorithm>中的reverse(_BIter, _BIter),函数传入的参数是两个迭代器,分别指向字符串的第一个元素和末尾。

#include <iostream>
#include <algorithm>
#include <string>

using namespace std;
int main()
{
    string str = "hello world";
    reverse(str.begin(), str.end());

    cout << str;       //"dlrow olleh"
    return 0;
}

第三种:使用string类中的逆向迭代器 rbegin()和rend()。注:如果想要反转vector对象中的元素也可用这种方法,利用构造函数构造一个vector对象。

#include <iostream>
#include <string>

using namespace std;
int main()
{
    string str = "hello world";
    //getline(cin, str);

    string strReverse(str.rbegin(), str.rend());
    cout << strReverse;          //"dlrow olleh"

    return 0;
}


版权声明:本文为a563562675原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。