如何在 C++ 中反转字符串

本文将介绍如何在 C++ 中反转字符串。

使用字符串构造函数来反转字符串

std::basic_string 有构造函数,它可以用范围内的内容构建一个字符串。然后,我们可以声明一个新的字符串变量,并向其构造函数提供原始字符串变量的反向迭代器-tmp_s。下面的例子演示了这个方法,并输出两个字符串进行验证。

#include <iostream>#include <string>#include <algorithm>using std::cout; using std::endl;
using std::string; using std::reverse;
int main(){
    string tmp_s = "This string will be reversed";
    cout << tmp_s << endl;
    string tmp_s_reversed (tmp_s.rbegin(), tmp_s.rend());
    cout << tmp_s_reversed << endl;
    return EXIT_SUCCESS;
}

输出:

This string will be reversed
desrever eb lliw gnirts sihT

使用 std::reverse() 算法反转字符串

std::reverse 方法来自 <algorithm>STL 库,它将范围内元素的顺序反转。该方法对作为参数传递的对象进行操作,并不返回数据的新副本,所以我们需要声明另一个变量来保存原始字符串。

需要注意的是,如果算法未能分配内存,reverse 函数会抛出 std::bad_alloc 异常。

#include <iostream>#include <string>#include <algorithm>using std::cout; using std::cin; using std::endl;
using std::string; using std::reverse;
int main(){
    string tmp_s = "This string will be reversed";
    cout << tmp_s << endl;
    string tmp_s_reversed(tmp_s);
    reverse(tmp_s_reversed.begin(), tmp_s_reversed.end());
    cout << tmp_s_reversed << endl;
    return EXIT_SUCCESS;
}

使用 std::copy() 算法反转字符串

std::copy 是另一种强大的算法,可以用于多种情况。该方案初始化一个新的字符串变量,并使用内置的 resize 方法修改其大小。接下来,我们调用 copy 方法,用原始字符串的数据填充声明的字符串。但要注意,前两个参数应该是源范围的反向迭代器。

#include <iostream>#include <string>#include <algorithm>using std::cout; using std::cin; using std::endl;
using std::string; using std::reverse;
int main(){
    string tmp_s = "This string will be reversed";
    cout << tmp_s << endl;
    string tmp_s_reversed;
    tmp_s_reversed.resize(tmp_s.size());
    copy(tmp_s.rbegin(), tmp_s.rend(), tmp_s_reversed.begin());
    cout << tmp_s_reversed << endl;
    return EXIT_SUCCESS;
}

在不需要存储反向字符串数据的情况下,我们可以使用 copy() 算法直接将字符串数据按反向顺序输出到控制台,如以下代码示例所示。

#include <iostream>#include <string>#include <algorithm>using std::cout; using std::cin; using std::endl;
using std::string; using std::reverse;
int main(){
    string tmp_s = "This string will be reversed";
    cout << tmp_s << endl;
    copy(tmp_s.rbegin(), tmp_s.rend(),
         std::ostream_iterator<char>(cout,""));
    return EXIT_SUCCESS;
}