I copied this off of www.csharphelp.com
int Reverse(char* str)
{
if (NULL==str)return -1; //no string
int l=strlen(str)-1; //get the string length
if (1==l)return 1;
for(int x=0;x < l;x++,l--)
{
str[x]^=str[l]; //triple XOR Trick
str[l]^=str[x]; //for not using a temp
str[x]^=str[l];
}
return 0;
}
Also, check out the following: http://www.daniweb.com/code/snippet117.html
cscgal
The Queen of DaniWeb
19,422 posts since Feb 2002
Reputation Points: 1,474
Solved Threads: 230
Don't use the physical size of the string as your limit, use the logical size. The physical size is the size of the array while the logical size is determined by where the terminating null character is:
#include <algorithm>
#include <cstring>
#include <iostream>
using namespace std;
void sreverse(char *s)
{
size_t begin = 0;
size_t end = strlen(s) - 1;
while (begin < end)
swap(s[begin++], s[end--]);
}
int main()
{
char s[20];
cout<<"Enter a string: ";
if (cin.getline(s, sizeof s)) {
sreverse(s);
cout<< s <<endl;
}
}
Or alternatively, straight printing as you were doing:
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char s[20];
cout<<"Enter a string: ";
if (cin.getline(s, sizeof s)) {
for (size_t i = strlen(s) - 1; i != 0; i--)
cout<< s[i];
cout<< s[0] <<endl;
}
}
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
Narue, I see in your example you use #include
I never heard of this library? I did a google search for algorithm.h and can't seem to find a listing of functions?
cscgal
The Queen of DaniWeb
19,422 posts since Feb 2002
Reputation Points: 1,474
Solved Threads: 230
>I never heard of this library?
It's a handy header . Among the functions that it gives you is swap, which saves everyone from that XOR abomination that your code displayed. *shudder* At least it wasn't undefined behavior the way you wrote it. Most people try to palm off the one-liner version:
a ^= b ^= a ^= b;
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
I was actually thinking that it probably did cover the swap function() which is why I did a google search for it. When I couldn't come up with a list of functions it included, I figured I'd just ask you directly. I'm going to recede back into my PHP world just about now :)
cscgal
The Queen of DaniWeb
19,422 posts since Feb 2002
Reputation Points: 1,474
Solved Threads: 230
>Narue, ever tought of becoming a teacher
Yes, but if it's anything like the "tutoring" I do with the programmers working under me, I would be fired in an instant for verbal abuse. ;) It's not that I'm really that bad, it's just that people are too touchy these days.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401