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.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check