C++ 如何通过内置的reverse()函数在C++中存储反转的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28345478/
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 store reversed string by inbuilt reverse() function in c++
提问by sneha sharma
how to reverse a string(not character array) using inbulit functionin c++.And i need to store original copy as well as reversed one so that i can compare them for equality.please let me know how to do this
如何在C++ 中使用 inbulit 函数反转字符串(不是字符数组)。我需要存储原始副本以及反转副本,以便我可以比较它们的相等性。请让我知道如何执行此操作
回答by const_ref
#include <algorithm>
std::string str1("original");
std::string str2(str1);
std::reverse(str2.begin(), str2.end());
if(str1 == str2)...
Take a copy of the original string, then use std::reverse to inplace reverse the copy. Then you can do a comparison on the two.
获取原始字符串的副本,然后使用 std::reverse 来反转副本。然后你可以对两者进行比较。
回答by NathanOliver
Make a copy of the string and then use the reverse function from the algorithm header.
复制该字符串,然后使用算法标题中的反向函数。
std::string original;
// put data in the string
std::string reversed(original);
std::reverse(reversed.begin(), reverse.end());
回答by SingerOfTheFall
std::reverse
operates in place, so if you want to keep both the original and the reversed strings, you will have to make a copy first, and then reverse it:
std::reverse
操作到位,所以如果你想同时保留原来的和反转的字符串,你必须先制作一个副本,然后反转它:
std::string original("foo");
std::string copy(original);
std::reverse(copy.begin(), copy.end());
回答by shauryachats
You could simply use the reverse()
function in <algorithm>
.
您可以简单地reverse()
在<algorithm>
.
std::string same("Hello world");
std::string reversed(same);
std::reverse(reversed.begin(),reversed.end());
//To compare them for equality..
if (same == reversed) {
...
}
回答by Ali
You do not need keep separate copy, you can access string in reverse order as follows:
您不需要保留单独的副本,您可以按相反的顺序访问字符串,如下所示:
string str = "Well Come";
for (unsigned i = str.size() - 1; i >= 0; i++)
cout << str.at(i);