如何反转std :: string?
当我以二进制数读取字符串时,我试图弄清楚如何反转字符串 temp
Im trying to figure out how to reverse the string temp
when I have the string read in binary numbers
istream& operator >>(istream& dat1d, binary& b1)
{
string temp;
dat1d >> temp;
}
推荐答案
我不确定你所说的包含二进制数的字符串是什么意思.但是要反转字符串(或任何与 STL 兼容的容器),您可以使用 std::reverse()
.std::reverse()
在原地运行,因此您可能需要先复制字符串:
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:
#include <algorithm>
#include <iostream>
#include <string>
int main()
{
std::string foo("foo");
std::string copy(foo);
std::cout << foo << '
' << copy << '
';
std::reverse(copy.begin(), copy.end());
std::cout << foo << '
' << copy << '
';
}
相关文章