Home > Enterprise >  indexOf second argument in Scala
indexOf second argument in Scala

Time:12-02

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

CodePudding user response:

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.

CodePudding user response:

indexOf(int ch, int fromIndex) looks for the character in the string from the specified index (fromIndex). This means it starts looking at 7th position.

CodePudding user response:

Going forward you need to learn to read the official docs: indexOf:

def indexOf(elem: A, from: Int): Int
[use case] Finds index of first occurrence of some value in this general sequence after or at some start index.

Note: may not terminate for infinite-sized collections.

elem
the element value to search for.

from
the start index

returns
the index >= from of the first element of this general sequence that is equal (as determined by ==) to elem, or -1, if none exists.

I personally like to use Intellij to jump into the source code with CMD B.

No matter how you take it: in your development flow you'll frequently access the manual\docs of the lib or lang you're using.

  • Related