Home »
Scala »
Scala Programs
Scala program to check the string starts with a specified substring
Here, we are going to learn how to check the string starts with a specified substring in Scala programming language?
Submitted by Nidhi, on May 22, 2021 [Last updated : March 10, 2023]
Scala – Check if String Starts with Substring
Here, we will create a string and then we will check the string starts with a specified substring using the startsWith() method. The startsWith() method returns Boolean value. It returns true if the string starts with a specified substring. Otherwise, it will return false.
Scala code to check the string starts with a specified substring
The source code to check the string starts with a specified substring is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.
// Scala program to check the string starts with
// specified substring
object Sample {
def main(args: Array[String]) {
var str1 = "Hello World";
var str2 = "Hello World";
if (str1.startsWith("World"))
println("String str1 starts with 'World'");
else
println("String str1 does not starts with 'World'");
if (str2.startsWith("Hello"))
println("String str2 starts with 'Hello'");
else
println("String str2 does not starts with 'Hello'");
}
}
Output
String str1 does not starts with 'World'
String str2 starts with 'Hello'
Explanation
In the above program, we used an object-oriented approach to create the program. And, we created an object Sample. Here, we defined main() function. The main() function is the entry point for the program.
In the main() function, we created two string variables str1, str2. Both strings are initialized with "Hello World". Then we check strings starts with specified substring using startswith() method and print the appropriate message on the console screen.
Scala String Programs »