C++ 如何反转 std::string?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4951796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to reverse an std::string?
提问by Kameron Spruill
Im trying to figure out how to reverse the string temp
when I have the string read in binary numbers
temp
当我以二进制数读取字符串时,我试图弄清楚如何反转字符串
istream& operator >>(istream& dat1d, binary& b1)
{
string temp;
dat1d >> temp;
}
回答by Max Lybbert
I'm not sure what you mean by a string that contains binary numbers. But for reversing a string (or any STL-compatible container), you can use std::reverse()
. std::reverse()
operates in place, so you may want to make a copy of the string first:
我不确定您所说的包含二进制数的字符串是什么意思。但是要反转字符串(或任何 STL 兼容的容器),您可以使用std::reverse()
. std::reverse()
就地操作,因此您可能需要先复制字符串:
#include <algorithm>
#include <iostream>
#include <string>
int main()
{
std::string foo("foo");
std::string copy(foo);
std::cout << foo << '\n' << copy << '\n';
std::reverse(copy.begin(), copy.end());
std::cout << foo << '\n' << copy << '\n';
}
回答by HighCommander4
Try
尝试
string reversed(temp.rbegin(), temp.rend());
EDIT: Elaborating as requested.
编辑:按要求详细说明。
string::rbegin()
and string::rend()
, which stand for "reverse begin" and "reverse end" respectively, return reverse iteratorsinto the string. These are objects supporting the standard iterator interface (operator*
to dereference to an element, i.e. a character of the string, and operator++
to advance to the "next" element), such that rbegin()
points to the last character of the string, rend()
points to the first one, and advancing the iterator moves it to the previouscharacter (this is what makes it a reverse iterator).
string::rbegin()
和string::rend()
分别代表“反向开始”和“反向结束”,将反向迭代器返回到字符串中。这些是支持标准迭代器接口的对象(operator*
取消对元素的引用,即字符串的一个字符,并operator++
前进到“下一个”元素),这样rbegin()
指向字符串的最后一个字符,rend()
指向第一个字符,并推进迭代器将其移动到前一个字符(这就是使它成为反向迭代器的原因)。
Finally, the constructor we are passing these iterators into is a string constructor of the form:
最后,我们将这些迭代器传入的构造函数是以下形式的字符串构造函数:
template <typename Iterator>
string(Iterator first, Iterator last);
which accepts a pair of iterators of any type denoting a range of characters, and initializes the string to that range of characters.
它接受一对表示字符范围的任何类型的迭代器,并将字符串初始化为该字符范围。