I want to understand what does second argument in indexOf in Scala mean for Strings?
object Playground extends App {
val g: String = "Check out the big brains on Brad!"
println(g.indexOf("o",7));
}
The above program returns: 25 which is something I am not able to understand why?
It is actually the index of last o but how is it related to 7? Is it like the second argument n returns the index of the occurence of nth character and if n exceeds with the number of occurences then it returns the index of last present element?
But if that’s the case then this doesn’t make sense:
object Playground extends App {
val g: String = "Check out the big brains on Brad!"
(1 to 7).foreach(i => println(s"$i th Occurence = ${g.indexOf("o",i)} "))
}
which outputs:
1 th Occurence = 6
2 th Occurence = 6
3 th Occurence = 6
4 th Occurence = 6
5 th Occurence = 6
6 th Occurence = 6
7 th Occurence = 25
Source: https://www.scala-exercises.org/std_lib/infix_prefix_and_postfix_operators
>Solution :
According to Scala String documentation, the second parameter is the index to start searching from:
def indexOf(elem: Char, from: Int): Int
Finds index of first occurrence of some value in this string after or at some start index.
elem : the element value to search for.
from : the start index
returns : the index >= from of the first element of this string that is equal (as determined by ==) to elem, or -1, if none exists.
Thus, in your case, when you specify 7, it means that you will look for the index of the first character "o" which is located at index 7 or after . And indeed, in your String you have two "o", one at index 6, one at index 25.