Search code examples
c++stringstdstring

fastest way to read the last line of a string?


I'd like to know the fastest way for reading the last line in a std::string object.
Technically, the string after the last occurrence of \n in the fastest possible way?


Solution

  • I would probably use std::string::rfind and std::string::substr combined with guaranteed std::string::npos wrap around to be succinct:

    inline std::string last_line_of(std::string const& s)
    {
        return s.substr(s.rfind('\n') + 1);
    }
    

    If s.rfind('\n') doesn't find anything it returns std::string::npos. The C++ standard says std::string::npos + 1 == 0. And returning s.substr(0) is always safe.

    If s.rfind('\n') does find something then you want the substring starting from the next character. Again returning s.substr(s.size()) is safe according to the standard.

    NOTE: In C++17 this method will benefit from guaranteed return value optimization so it should be super efficient.