Reverse C-style String? - C++

前端 未结 5 491
陌清茗
陌清茗 2021-01-01 06:10

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 efficie

5条回答
  •  借酒劲吻你
    2021-01-01 06:31

    Assuming you can't use anything but C string functions, I would

    • avoid pre-declaring variables at the beginning of the function. This is a requirement of C (with the 1990 standard), but in C++ it is more idiomatic to declare and initialize variables where you use them.

    • avoid going out of bounds (decrementing beyond start of string) if the string is empty.

    So something like:

    void reverse(char* string)
    {
        char* first = string;
        char* last = string + strlen(string);
    
        while(first < last)
        {
            --last; //avoids decrementing last beyond start of string if string is empty
            char temp = *first;
            *first = *last;
            *last = temp;
            ++first;
        }
    }
    

提交回复
热议问题