Start learning free

LESSON 58 OF 677 · STRINGS I

String Slicing in Scala

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 substring() method like this:

string.substring(startIndex, endIndex)

This is called slicing a string. It returns the substring from startIndex to endIndex.

Here is an example:

var language = "Scala"
var substring = language.substring(1, 4)

println(substring) // Output: cal
println(language) // Output: Scala

The startIndex is a zero-based index at which we start extraction and the endIndex is also zero-based index before which we end the extraction.

The substring will not include the character at endIndex. You can see in our example that the character at index 1 (c) was included while the character at index 4 (a) was excluded.

Also 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 endIndex, substring() extracts to the end of the string:

var language = "Scala"
var substring = language.substring(2)

println(substring) // Output: ala

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