CTCI: Ch. 1-2

Implement a function void reverse(char* str) in C or C++ which reverses a null-terminated string.

#include <iostream>
#include <string.h>
using namespace std;
void reverse(char* str);

void reverse(char* str)
{
    char tmp;
    for(int i=0;i<strlen(str)/2;i++)
    {
        tmp = str[strlen(str)-i-1];
        str[strlen(str)-i-1] = str[i];
        str[i] = tmp;
    }
    
}

int main(int argc, const char * argv[])
{
    char ch[]="12345678\0";
    reverse(ch);
    cout<<ch<<endl;
    return 0;
}

 

Leave a Reply