Reverse C-style String? - C++

arrays, c++, pointers

Solution

void str_reverse( char *str ) {
    char *str_end = strchr( str, 0 );
    std::reverse( str, str_end );
}

if you're supposed to write a loop,

void str_reverse( char *str ) {
    std::size_t len = std::strlen( str );
    for ( std::size_t index = 0; index != len / 2; ++ index ) {
        std::swap( str[ index ], str[ len - index - 1 ] );
    }
}

or, of course, if you can use a C++ string,

void str_reverse( std::string &str ) {
    std::reverse( str.begin(), str.end() );
}

Problem

I want to use pointers to reverse a char array in C++. I was wondering if there is anything that I should do differently? Am I doing this correctly? Is there a more efficient way to accomplish this? My small program: ``` int main ( ) { char buffer[80]; PrintHeader(); cout << "\nString reversal program"; cout << "\nType in a short string of words."; cout << "\nI will reverse them."; cout << "\n:"; cin.getline(buffer, 79); cout << "\nYou typed " << buffer; reverse (buffer); cout << "\nReversed: " << buffer; cout << endl; system("PAUSE"); return 0; } void reverse(char* string) { char* pStart, *pEnd; int length; char temp; length = strlen(string); pStart = string; pEnd = &string[length - 1]; while(pStart < pEnd) { temp = *pStart; *pStart = *pEnd; *pEnd = temp; pStart++; pEnd--; } } ```

Original source

Related problems