C++ equivalent of Python String Slice?

Yes, it is the substr method:

basic_string substr( size_type pos = 0,
                     size_type count = npos ) const;
    

Returns a substring [pos, pos+count). If the requested substring extends past the end of the string, or if count == npos, the returned substring is [pos, size()).

Example

#include <iostream>
#include <string>

int main(void) {
    std::string text("Apple Pear Orange");
    std::cout << text.substr(6) << std::endl;
    return 0;
}

See it run

Leave a Comment

tech