How to create substrings of a string in Scala? String substring() Method

Here, we will learn about the substring() method in Scala. It is used to create a substring from the starting index to ending index.
Submitted by Shivang Yadav, on January 29, 2021

String is an immutable collection that stores sequences of characters.

String substring() Method

The substring() method is used to create a substring from the string from the startingIndex to endingIndex.

Syntax:

string_name.substring(startingIndex, endingIndex)

Parameters: The method accepts two parameters,

  • The starting Index of the substring to be created.
  • The ending Index of the substring to be created.

Return Value: It returns a string which is the substring of the given string.

Note: Here, you might be confused that the same function is performed by the subsequence() method in Scala. But there's a difference in the return type of both methods. The substring() method returns a string whereas the subsequence() method returns a charSequence.

We will see an example here to see the difference between both the method.

Example 1: Crating a substring within the given index range

object myObject {
    def main(args: Array[String]) {
        val myString = "Scala Programming language"
        println("The string is '" + myString + "'")
        
        val subString = myString.substring(0, 6)
        println("The substring created is '" + subString + "'")
    }
}

Output:

The string is 'Scala Programming language'
The substring created is 'Scala '

Example 2: Program to see the difference between the substring() and subSequence() method

object myObject {
    def main(args: Array[String]) {
        val myString = "Scala Programming language"
        println("The string is '" + myString + "'")
        
        val subString = myString.substring(0, 5)
        println("\nThe substring created is '" + subString + "'")
        
        val subSeq = myString.subSequence(0, 5)
        println("The subsequence created is '" + subSeq + "'")
        
        println(subString[3])
        println(subSeq[3])
    }
}

Output:

scala:12: error: value subString of type String does not take type parameters.
        println(subString[3])
                         ^
scala:13: error: value subSeq of type CharSequence does not take type parameters.
        println(subSeq[3])
                      ^

Here, we need to have intentionally accessed the values in the wrong way. This prompts an error showing the type of both the values. That shows substring() returns a string and subsequence() returns a CharSequence.



Comments and Discussions!

Load comments ↻





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