Search code examples
pythonc++object-slicing

How to do python style string slicing in c++


Is it possible to implement a method through which I can do slicing in C++ using : operator.

For example,I define a C-style string as shown below:

char my_name[10] {"InAFlash"};

Can I implement a function or override any internal method to do the following:

cout << my_name[1:5] << endl;

Output: nAFl

Update 1: i tried with string type as below

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string my_name;
    my_name = "Hello";
    // strcpy(my_name[2,5],"PAD");
    // my_name[2]='p';
    cout << my_name[2:4];
    return 0;
} 

But, got the following error

helloWorld.cpp: In function 'int main()':
helloWorld.cpp:10:22: error: expected ']' before ':' token
     cout << my_name[2:4];
                      ^
helloWorld.cpp:10:22: error: expected ';' before ':' token

Solution

  • If you want a copy of the string, then it can be done using iterators or substr:

    std::string my_name("InAFlash");
    std::string slice = my_name.substr(1, 4); // Note this is start index, count
    

    If you want to slice it without creating a new string, then std::string_view (C++17) would be the way to go:

    std::string_view slice(&my_name[0], 4);