Jump to content
  • Advertisement
Sign in to follow this  
TEUTON

reversing a string

This topic is 4515 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Question goes like this How will you reverse a C-string without using any temporary variables? I tried this

#include <iostream>
#include<string>
int main()
{
	
char *str="dumbo";
std::cout<<strrev(str);
return 0;
}
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.

Share this post


Link to post
Share on other sites
Advertisement
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.

Share this post


Link to post
Share on other sites
oh yeah...
That would just print in reverse order..I am still thinking of a way without using temporary variable.

Share this post


Link to post
Share on other sites
For printing it backwards, I'd try this:


#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.

Share this post


Link to post
Share on other sites
Nice...they should work fine.
I'll just post my attempt of writing reverse function without temporary variable

Share this post


Link to post
Share on other sites
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;
}
}

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!