Is there an equivalent to string / list slicing in C++, like in Python?

Question:

I’m learning C++ whilst being fairly good at Python. Is there a slicing equivalent in C++ like in Python?

# Python

person = "Jimmy"
print(person[1:-1]) # imm
// c++

#include <iostream>
#include <string>

using namespace std;

int main(){
    string name = "Jimmy";
    cout << name[1:-1] << endl; // imm
}

Thanks

Here is the error:

`

random.cpp: In function 'int main()':
random.cpp:8:19: error: expected ']' before ':' token
     cout << name[1:-1] << endl; // imm
                   ^
random.cpp:8:19: error: expected ';' before ':' token

`

Asked By: Bingus

||

Answers:

Yes, C++ provides a way to slice strings in a similar way to Python using the substr function from the string library.

Here is an example of how you can use substr to slice a string in C++:

#include <iostream>
#include <string>

int main() {
    std::string s = "Hello, world!";

    // Get a slice of the string from the 7th character to the end
    std::string slice = s.substr(7);

    std::cout << slice << std::endl;  // prints "world!"

    return 0;
}

The substr function takes two arguments: the starting index of the slice and the length of the slice. If you omit the length argument, substr will return the slice from the starting index to the end of the string.

Answered By: Mustapha Hadid
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.