What is the substring method in Scala?
Scala offers many functions for string manipulation, the substring function being one of them. We can use the substring function to take out a required part of a string, using the starting index.
Syntax
String substring(int startIndex, int endIndex)
Parameter
The substring function takes two parameters: the index at which the required part of the string starts, and the index at which it ends.
Return value
The substring function returns the substring that begins at the specified index and ends at the specified index (or at the end of the main string, if the end index is not specified).
Code
The following code shows the implementation of the substring function.
// Example code for substring() functionobject Main extends App{// Using substring function without end indexval sub_string = "This is an Edpresso shot".substring(11)// Using substring function with end indexval sub_string2 = "This is an Edpresso shot".substring(11, 15)// Displays the substringsprintln(sub_string)println(sub_string2)}
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved