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
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.
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.
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.
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.
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()).
#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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With