Reverse String C++ using char array

前端 未结 5 629
暖寄归人
暖寄归人 2020-12-03 01:52

I wrote a simple C++ program to reverse a string. I store a string in character array. To reverse a string I am using same character array and temp variable to swap the char

5条回答
  •  青春惊慌失措
    2020-12-03 02:25

    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

    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

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

提交回复
热议问题