Reverse a string

Reverse a string in place
/*
 * ReverseString.cpp
 *
 *  Created on: Apr 9, 2012
 *      Author: Kiran Hegde
 */

#include <iostream>

void reverse(char *str) {
    char *end = str;
    char tmp;
    if (str) {
        while(*end)
            ++end;
    }
    --end;
    while (str < end) {
        tmp = *str;
        *str++ = *end;
        *end-- = tmp;
    }
}

/**
 * Test the function
 */
using namespace std;

int main() {
    char str[] = "Reverse Me Now";
    cout << "Original: " << str << endl;
    reverse(str);
    cout << "Reverse: " << str << endl;
    return 0;
}
Comments