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


std::string text = "Apple Pear Orange";
std::cout << std::string(text.begin() + 6, text.end()) << std::endl;  // No range checking at all.
std::cout << text.substr(6) << std::endl; // Throws an exception if string isn't long enough.

Note that unlike python, the first doesn't do range checking: Your input string needs to be long enough. Depending on your end-use for the slice there may be other alternatives as well (such as using an iterator range directly instead of making a copy like I do here).


In C++ the closest equivalent would probably be string::substr(). Example:

std::string str = "Something";
printf("%s", str.substr(4)); // -> "thing"
printf("%s", str.substr(4,3)); // -> "thi"

(first parameter is the initial position, the second is the length sliced). Second parameter defaults to end of string (string::npos).

Tags:

Python

C++

String