Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

indexOf second argument in Scala

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading