String Slicing

String slicing allows you to extract a portion of a string.

It takes two parameters: the starting index and the ending index (optional). It returns a new string containing the extracted portion.

Let's perform such operations on the string "computer". It's structure is the following:

string-slicing-structure

Single argument slicing

Skip the first couple of symbols

Output:

In this example, str.substring(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.

Selecting the last couple of symbols

Output:

In this example, str.substring(str.length() - 3) extracts only the last 3 symbols of the string - 't', 'e', and 'r'.

The way it works it 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:

Two arguments slicing

Allows selecting symbols in certain range.

Output:

In this example, str.substring(3, 5) skips the first 3 symbols of the string - 'c', 'o', and 'm'.

Afterwards, it takes the rest of the string until it reaches the 5th symbol - '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() - 1 is the same as 8 - 1 which is 7. So it take the rest of the string until the symbol at the 7th index is reached - r.

Invalid cases

An invalid case results in exception.

It's using indexes outside of the string bounds.

Such an example is using negative indexes:

Another example which throws exception is using positive index that's outside of the string bounds.