#include <iostream>
#include<string>
int main()
{
char *str="dumbo";
std::cout<<strrev(str);
return 0;
}
reversing a string
Question goes like this
How will you reverse a C-string without using any temporary variables?
I tried this
But it didn't work but it works for str[]...I guess I understad the reason.
because it's readonly.
can't think of any other way without using temporary.
Do you want to actually reverse the string, or just print the characters in reverse order?
You can't reverse the string in your example, because str is pointing to read-only memory. Seriously.
You can't reverse the string in your example, because str is pointing to read-only memory. Seriously.
oh yeah...
That would just print in reverse order..I am still thinking of a way without using temporary variable.
That would just print in reverse order..I am still thinking of a way without using temporary variable.
For printing it backwards, I'd try this:
For reversing the string itself, I'd try this:
If for some reason using the STL isn't allowed, then I'm going to assume this is homework and I shouldn't be helping you.
#include <iostream>#include <iterator>#include <algorithm>#include <cstring>int main(){ const char *str = "Hello World!"; std::reverse_copy(str, str+std::strlen(str), std::ostream_iterator<char>(std::cout));}
For reversing the string itself, I'd try this:
#include <iostream>#include <algorithm>#include <cstring>int main(){ char str[] = "Hello World!"; std::reverse(str, str+std::strlen(str)); std::cout << str;}
If for some reason using the STL isn't allowed, then I'm going to assume this is homework and I shouldn't be helping you.
Nice...they should work fine.
I'll just post my attempt of writing reverse function without temporary variable
I'll just post my attempt of writing reverse function without temporary variable
maybe its just my bias, but i like my solution the best
void strrev(char *src){ char *ptr; for (ptr = src; *ptr; ++ptr); --ptr; while (src < ptr) { *src ^= *ptr ^= *src ^= *ptr; --ptr; ++src; }}
Why are you using arrays of characters?
std::string s = "blah";
std::reverse( s.begin(), s.end() );
std::string s = "blah";
std::reverse( s.begin(), s.end() );
Quote:Original post by Thetan
maybe its just my bias, but i like my solution the best
I hope I never have to maintain your code. [wink]
Seriously though, the standard library is your friend.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement