Reverse C-style String? - C++

前端 未结 5 466
陌清茗
陌清茗 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:47

    void str_reverse( char *str ) {
        char *str_end = strchr( str, 0 );
        std::reverse( str, str_end );
    }
    

    if you're supposed to write a loop,

    void str_reverse( char *str ) {
        std::size_t len = std::strlen( str );
        for ( std::size_t index = 0; index != len / 2; ++ index ) {
            std::swap( str[ index ], str[ len - index - 1 ] );
        }
    }
    

    or, of course, if you can use a C++ string,

    void str_reverse( std::string &str ) {
        std::reverse( str.begin(), str.end() );
    }
    

提交回复
热议问题