DEV Community 👩‍💻👨‍💻

vicky-ops
vicky-ops

Posted on

SubArray/SubString

Sub Array/Sub Strings

A Sub array or a subString is **contiguous part** of array/strings.
subarray's are part of like array's with in array's.
Let's look into some example

Find the substrings of "masai":
 The total number of non-empty substrings are 15 . You might ask how? lets find it mathmetical way
Enter fullscreen mode Exit fullscreen mode
     //Given string
     let str = "masai";
    // finding the length/total element
     let n = str.length
     //Once we have total count of element which is 5 here
     // the formula is easy n*n+1/2
    //  So that's it lets apply the formula here
    // so here n=5 according to the formula
    // 5*5+1/2 = 15
    // so total of non-empty sub-stings will be 15
Enter fullscreen mode Exit fullscreen mode
 Formula is n*n+1/2
 n is the total count of element/length

 Now lets find the substrings of the string on pen and paper
Enter fullscreen mode Exit fullscreen mode
Here is the list of possible substrings of the string
'm' 
'm' 'a' 
'm' 'a' 's' 
'm' 'a' 's' 'a' 
'm' 'a' 's' 'a' 'i' 
'a' 
'a' 's' 
'a' 's' 'a' 
'a' 's' 'a' 'i' 
's' 
's' 'a' 
's' 'a' 'i' 
'a' 
'a' 'i' 
'i' 
Enter fullscreen mode Exit fullscreen mode
There we have it exactly 15 sub-strings.

Anyway Here is the javascript implementation to get substings.
Enter fullscreen mode Exit fullscreen mode
let str = "masai";
for(let i = 0;i<str.length;i++){
  let str1 = "";
  for(let j=i;j<str.length;j++){
    str1+=str[j];
    console.log(str1)
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Just kidding, it's a personal preference. But you can change your theme, font, etc. in your settings.

The more you know. 🌈