pythonc++string

C++ equivalent of Python string slice


In Python, I was able to slice part of a string; in other words just print the characters after a certain position. Is there an equivalent to this in C++?

Python code:

text = "Apple Pear Orange"
print text[6:]

Would print: Pear Orange


Solution

  • 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


    If you can use C++17, use a string_view to avoid a copy:

    std::string_view(text).substr(6)
    

    If you can use C++20, now we have ranges. See other answers for more information.