How to get all substrings of given string input in scala
admin
#How to get all substrings of given string input #scala #program #Scala nested loops, #Scala code examples #generate substrings in Scala
In this article, we will explore a Scala program to generate all possible substrings of a given string. This problem demonstrates the use of nested loops and the substring
method in Scala, which is ideal for string manipulation tasks.
The implementation employs two nested loops:
Outer Loop: Iterates through the starting index (i
) of the substrings.
Inner Loop: Iterates through all possible ending indices (j
) of the substrings, starting from the current index i
.
For each combination of starting and ending indices, the substring
method extracts the substring from the string, which is then added to the list of substrings.
Below is the Scala program that solves this problem:
object MyDeveloper {
def main(args: Array[String]): Unit = {
def get_all_substrings(string: String): Unit = {
var substrings = List[String]()
val len = string.length - 1
var substring = ""
for (i <- 0 to len) {
for (j <- i to len) {
substring = string.substring(i, j + 1)
println(substring)
substrings ++= List(substring)
}
}
substrings
}
// Example usage
get_all_substrings("example")
}
}
String: "example"
The substrings of the string "example"
are:
e
ex
exa
exam
examp
exampl
example
x
xa
xam
xamp
xampl
xample
a
am
amp
ampl
ample
m
mp
mpl
mple
p
pl
ple
l
le
e
get_all_substrings
Method:
Accepts a string as input.
Initializes an empty list substrings
to store the substrings.
The outer loop starts from index 0
and iterates up to the last index of the string.
The inner loop generates all possible ending indices for the current starting index and extracts substrings using the substring(i, j + 1)
method.
Adding Substrings to the List:
Each generated substring is printed and added to the substrings
list using the ++=
operator.
Example Execution:
For the string "example"
, the program iteratively generates all possible substrings by varying the starting and ending indices.
In this article, we demonstrated how to generate all substrings of a given string in Scala. The approach leverages nested loops and the substring
method to extract substrings systematically. The substrings are collected in a list for further processing.
This solution highlights the power of Scala's string manipulation methods and its efficient looping constructs, making it an excellent choice for tackling similar problems.
Feel free to reach out if you have any questions or need further assistance!