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

前端 未结 30 2298
长发绾君心
长发绾君心 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:35

    Another C++ way (though I would probably use std::reverse() myself :) as being more expressive and faster)

    str = std::string(str.rbegin(), str.rend());
    

    The C way (more or less :) ) and please, be careful about XOR trick for swapping, compilers sometimes cannot optimize that.

    In such case it is usually much slower.

    char* reverse(char* s)
    {
        char* beg = s, *end = s, tmp;
        while (*end) end++;
        while (end-- > beg)
        { 
            tmp  = *beg; 
            *beg++ = *end;  
            *end =  tmp;
        }
        return s;
    } // fixed: check history for details, as those are interesting ones
    

提交回复
热议问题