String slicing allows you to extract a portion of a string.
It takes two parameters: the starting index and the length (optional). It returns a new string containing the extracted portion.
Let's perform such operations on the string "computer". Its structure is the following:
Output:
In this example, str.substr(3)
skips the first 3
symbols of the string - 'c', 'o', and 'm'.
The remaining part of the string (starting from the 3rd index - 'p') is extracted - puter
.
Output:
In this example, str.substr(str.length() - 3)
extracts only the last 3 symbols of the string - 't', 'e', and 'r'.
The way it works is simply skipping the first 5 symbols.
str.length()
is the count of the string symbols - 8 in this case.
The code is absolutely the same as this:
Output:
Allows selecting symbols in a certain range.
Output:
In this example, str.substr(3, 2)
skips the first 3
symbols of the string - 'c', 'o', and 'm'.
Afterwards, it takes 2 symbols - p
and u
.
This way we can also skip the first and last characters like this:
Output:
In this example, 1
skips the first character - c
.
str.length() - 2
is the same as 8 - 2 which is 6. So it takes the rest of the string until 6 symbols are taken.
An invalid case results in an exception.
It uses indexes outside of the string bounds.
Such an example is using negative starting index:
Another example which throws an exception is using a positive index that's outside of the string bounds.
Specifying negative second argument results in the same string as specifying only a single argument:
Output: