Reverse String C++ using char array

sizeof(str) does not do what you expect.

Given a char *str, sizeof(str) will not give you the length of that string. Instead, it will give you the number of bytes that a pointer occupies. You are probably looking for strlen() instead.

If we fixed that, we would have:

for(i=0;i<strlen(str)/2;i++)
{
    char temp=str[i];
    str[i]=str[strlen(str)-i-1];
    str[strlen(str)-i-1]=temp;
}

This is C++, use std::swap()

In C++, if you want to swap the contents of two variables, use std::swap instead of the temporary variable.

So instead of:

char temp=str[i];
str[i]=str[strlen(str)-i-1];
str[strlen(str)-i-1]=temp;

You would just write:

swap(str[i], str[sizeof(str) - i - 1]);

Note how much clearer that is.

You’re using C++, just use std::reverse()

std::reverse(str, str + strlen(str));

Global variables

It’s extremely poor practice to make variables global if they don’t need to be. In particular, I’m referring to i about this.

Executive Summary

If I was to write this function, it would look like one of the two following implementations:

void reverseChar(char* str) {
    const size_t len = strlen(str);

    for(size_t i=0; i<len/2; i++)
        swap(str[i], str[len-i-1]);
}

void reverseChar(char* str) {
    std::reverse(str, str + strlen(str));
}

When tested, both of these produce dlrow olleh on an input of hello world.

Leave a Comment