How to do python style string slicing in c++

Question:

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
Asked By: rawwar

||

Answers:

If you are stuck with C-style array, std::string_view (C++17) could be a good way to manipulate char[] without copying memory around:

#include <iostream>
#include <string_view>

int main()
{
    char my_name[10] {"InAFlash"};
    std::string_view peak(my_name+1, 4);
    std::cout << peak << 'n'; // prints "nAFl"
} 

Demo: http://coliru.stacked-crooked.com/a/fa3dbaf385fd53c5


With std::string, a copy would be necessary:

#include <iostream>
#include <string>

int main()
{
    char my_name[10] {"InAFlash"};
    std::string peak(my_name+1, 4);
    std::cout << peak << 'n'; // prints "nAFl"
} 

Demo: http://coliru.stacked-crooked.com/a/a16112ac3ffcd8de

Answered By: YSC

If you use std::string (the C++ way) you can

std::string b = a.substr(1, 4);
Answered By: schorsch312

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);
Answered By: Yuushi
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.