How do you reverse a string in place in C or C++?

前端 未结 30 2284
长发绾君心
长发绾君心 2020-11-22 00:37

How do you reverse a string in C or C++ without requiring a separate buffer to hold the reversed string?

30条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 01:18

    Share my code. As a C++ learner, as an option to use swap(), I am humbly asking for comments.

    void reverse(char* str) {
        int length = strlen(str);
        char* str_head = str;
        char* str_tail = &str[length-1];
        while (str_head < str_tail) 
            swap(*str_head++, *str_tail--);
    }
    

提交回复
热议问题