Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ equivalent of Python String Slice?

Tags:

c++

python

string

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

like image 210
David.Sparky Avatar asked Jan 16 '15 20:01

David.Sparky


People also ask

Is string slicing possible in C?

Splitting a string using strtok() in CIn C, the strtok() function is used to split a string into a series of tokens based on a particular delimiter. A token is a substring extracted from the original string.

Does C++ have string slicing?

The substr() function is defined in the string. h header and is used for string slicing in C++. It can be used to extract a part of a string, i.e., get a substring. A substring is a sequence of consecutive characters from a string.

Can you slice a string in Python?

Python string supports slicing to create substring. Note that Python string is immutable, slicing creates a new substring from the source string and original string remains unchanged.

What is the slicing in Python?

Definition and Usage The slice() function returns a slice object. A slice object is used to specify how to slice a sequence. You can specify where to start the slicing, and where to end. You can also specify the step, which allows you to e.g. slice only every other item.


1 Answers

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

like image 98
whoan Avatar answered Sep 22 '22 19:09

whoan