vicky-ops

Posted on

# 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
//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
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
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'
There we have it exactly 15 sub-strings.

Anyway Here is the javascript implementation to get substings.
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)
}
}