1

I want to slice array of character in c++ or simply equivivalent code of python code given below.

s1 = ["A", "B", "C" , "D" , "E"]
s2 = s1[0:2] 

s2 ==> ["A","B"]
s1 ===> ["A", "B", "C" , "D" , "E"]
2
  • 2
    What's your question? Commented Sep 27, 2013 at 22:08
  • I got my answer, i wanted to perform above task in c++ Commented Sep 27, 2013 at 22:25

2 Answers 2

4

You should use std::string objects while working with strings and for retrieving some part of the string you can use std::string::substr:

std::string s1("ABCDE");
std::string s2 = s1.substr(0, 2);
Sign up to request clarification or add additional context in comments.

2 Comments

Slices don't refer to the same array, rather they refer to the same array contents.
@aaronman Wrong, in Python a slice is a new object (although Python strs, being immutable, use the same memory behind the scenes).
0

std::string_View is the answer if you are using a C++17 compiler. See Get part of a char array

auto s1 = "ABCDE";
auto s2 = std::string_view{s1, 2}; // AB

If you don't want to start at position 0, you can move the pointer further along and slice from there:

auto s2 = std::string_view{s1 + 2, 2}; // CD

Unfortunately, there is currently no option for changing the step value, as with python

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.