Scala String indexOf() Method with Example

Here, we will learn about the indexOf() method of String in Scala. It is used to find the index of the first occurrence of the given substring. We will see its working, syntax and example.
Submitted by Shivang Yadav, on February 03, 2021

String is an immutable collection that stores sequences of characters.

String indexOf() Method

The indexOf() method on strings is used to find the index where the given substring is encountered in the string for the first time.

You can optionally provide the starting index of the search of the substring using offSet parameter.

The indexOf() method can also be used to check for the occurrence of character in the string, you just need to replace the substring with the character.

Syntax:

For substring,
    string_Name.indexOf(string substring, int offSet)
For character, 
    string_Name.indexOf(char ch, int offSet)

Parameters: The method accepts two parameters, one mandatory and other optional.

Return Value: It returns an integer which is the index where the substring is found for the first time in the string.

Example 1:

object myObject {
    def main(args: Array[String]) {
        val string1 = "scala programming language "
        val indexVal = string1.indexOf("lang")
    
        println("The index of first occurrence of the substring is " + indexVal)
    }
}

Output:

The index of first occurrence of the substring is 18

Example 2:

object myObject {
    def main(args: Array[String]) {
        val string1 = "absfssssaabcsfsreab"
        val indexVal = string1.indexOf("ab", 4)
    
        println("The index of first occurrence of the substring is " + indexVal)
    }
}

Output:

The index of first occurrence of the substring is 9

The first index of occurrence here is 9, as the offSet is 4 i.e., any occurrence of the substring before the 4th index is ignored. If this was not the case, the method would have returned 0.

Example 3: Program to illustrate the working of indexOf() method for character

object myObject {
    def main(args: Array[String]) {
        val string1 = "scala"
        val indexVal = string1.indexOf("l")
    
        println("The index of first occurrence of the character is " + indexVal)
    }
}

Output:

The index of first occurrence of the character is 3



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.