How to get all substrings of given string input in scala

admin

6/20/2023
All Articles

#How to get all substrings of given string input #scala #program

How to get all substrings of given string input in scala

How to get all substrings of given string input in Scala Program 

In this Article, the outer loop iterates through the substring's initial index (i) at the beginning.
All potential ending index (j) are provided by the inner loop, which iterates from index i to the end of the string.
The substring is taken from index i to index j, and it is added to the list of substrings.
 
Below is Code of above problem .
 
 
object MyDeveloper {
def main(args: Array[String]): Unit = {
   
    def get_all_substrings(string:String){
    var substrings = List()
    val len = string.length-1
    var substring= ""
    println(len)
    for ( i  <- 0 to len ){
        for ( j <- i to len){
            substring = string.substring(i,j+1)
            println(substring)
            substrings ++: substring
        }
     }
 
     substrings
    
     }
   
     get_all_substrings("example")
   
   }
  }
 
 

Ouput of Above problem 

Input is String that is : "example"

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

 

Conclusion  :

Here we implemennt problem using scala language .
Aproch is like we are loop give string with 2 loop and using method subString(first index , last index) 
based on logic we get all substring in form of List collection .
 

Kindly feel free if you have any query  .