Reverse a character array [duplicate]
Possible Duplicate:
C++ Reverse Array
How can I reve开发者_JAVA百科rse a character array? Like this:
char word1[10] = "this";
char word2[10] = word1[10] // in reverse
cout<<word2; // I want it to output "siht"
std::string word1 = "this";
std::string word2 = word1;
std::reverse(word2.begin(), word2.end());
std::cout << word2;
How about a simple loop (since i do not know the exact type of word1
and word2
)?
for (int i = 0, k = 9; i < 10; i++, k--) {
word2[k] = word1[i];
}
I highly suggest that you use std::string
instead of char
. There are plenty of answers on how to do this with std::string
here.
I'd hazard something like the following:
- Copy
word1
toword2
, usingstd::copy
std::reverse
with word2 begin to end
and now word2
contains reverse, can't say more without knowing types.
Use a string reverse function to perform the same.
If word1 and word2 are char arrays, then nope. If instead word1 and word2 were some sort of object with a capacity of 10, you could just override the assignment operator.
int main(int, char**) {
std::string word1 = "beef";
std::string word2(word1.rbegin(), word1.rend());
std::cout << word2;
}
http://ideone.com/drunA
std::reverse_copy(word1, word1+10, word2);
精彩评论