Start learning free

LESSON 61 OF 348 · STRINGS I

String Find in Scala in Scala

Lesson

In Scala, you can find the index of a substring using indexOf():

s.indexOf(sub)           // returns index of first occurrence, or -1 if not found
s.lastIndexOf(sub)       // returns index of last occurrence
s.indexOf(sub, fromIdx)  // search starting from index `fromIdx`

Here are some examples:

var sentence = "Hello World"
var idx = sentence.indexOf("World")
println(idx)  // 6

println(sentence.indexOf("xyz"))  // -1  (not found)

The index returned is the position of the first character of the found substring.


Assignment
Follow the Coding Tutorial and find the index of "World" in sentence!


Hint
Use sentence.indexOf("World") and assign the result to idx.

STEP 1 OF 1
    Ctrl + Enter to check

    String Find in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free