Start learning free

LESSON 57 OF 667 · STRINGS I

String Slicing in C++

Lesson

Not only we can select a single character from a string, but we can also select a sequence of consecutive characters (e.g. substring) from a string.

To achieve this, we use the substr() method like this:

string.substr(startIndex, length);

This is called slicing a string. It returns the substring that starts at startIndex and has size length.

Here is an example:

string language = "JavaScript";
string substring = language.substr(2, 4);

cout << substring << endl; // Output: "vaSc"
cout << language << endl; // Output: "JavaScript"

Notice that language preserved its value. The slicing does not affect the original string. It just creates a brand new one representing the sliced substring.


If you omit the length, the substr() extracts to the end of the string:

string language = "JavaScript";
string substring = language.substr(4);

cout << substring; // Output: "Script"

Assignment
Follow the Coding Tutorial and let's slice some strings!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check