×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Scala String substring() Method

By IncludeHelp Last updated : October 21, 2024

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: 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.