Working through some programming interview challenges I found online, I had to write an algorithm to reverse a const char * and return a pointer to a new char *. I think I have it, but to make it work properly I had to do some wonky stuff - basically having to account for the null-terminating character myself. Somehow I feel this is wrong, but I'm stumped, and I was wondering if someone could help me out:
char * reverse(const char * str)
{
int length = strlen(str);
char * reversed_string = new char[length+1];
for(int i = 0; i < length; ++i)
{
reversed_string[i] = str[(length-1) - i];
}
//need to null terminate the string
reversed_string[length] = '\0';
return reversed_string;
}
int main(int argc, char * argv[])
{
char * rev_str = reverse("Testing");
cout << "Your string reversed is this: " << rev_str << endl;
delete rev_str;
rev_str = 0;
return 0;
}
this works nicely:
I had this question once. That's the first answer that comes to mind, but the follow-up is, "now do it without allocating any memory."
EDIT: Some folks have expressed disdain for not using pointers. This is a tiny bit more readable, though not completely optimal. Others have entered the pointer solution, so I won't repeat it here.
One commenter challenged that it should be doable without a (stack based) holding cell for the swap. The mechanism for doing that is bitwise XOR. Replace the inside of the loop with
But in general, modern compilers can optimize out the local variable of a naive swap. For details, See Wikipedia
String reversed in place, no temp variable.
Your code is straight forward and unsurprising. A few things:
In other words:
Uh? No one did it with pointers?
Hopefully years of Java haven't ruined my C ;-)
Edit: replaced all those strlen calls with an extra var. What does strlen return these days? (Thanks plinth).
@Konrad Rudolph: (sorry I don't have the "experience" to post a comment)
I want to point out that the STL supplies a reverse_copy() algorithm, similar to reverse(). You need not introduce a temporary the way you did, just allocate a new char * of the right size.