# Count of sub-strings of length n possible from the given string in C++

We are given a string str[] and a number n. The goal is to find all substrings of str[] that have length n. If string is “abcde” and n=3 then substrings of length 3 are “abc”, “bcd”, “cde” and count is 3.

Let us understand with examples.

Input − str[] = “computer” n=4

Output − Count of substrings of length n possible from the given string are − 5

Explanation − Substrings with length 4 are: “comp”, “ompu”,”mput”, “pute”, “uter”

Input − str[] = “development” n=5

Output − Count of substrings of length n possible from the given string are − 7

Explanation − Substrings with length 5 are: “devel”, “evelo”, “velop”, “elopm”, “lopme”, “opmen”, “pment”.

## Approach used in the below program is as follows

If we take the length of string str[] as L then the count of substrings of length n inside str[] is Ln+1. If string is “abcdefghi” and n is 4 then substrings will be “abcd”, “bcde”, “cdef”, “defg”, “efgh”, “fghi”. Count is 6. Also 9-4+1=6.

• Take a string str.

• Take n as integer.

• Function possible_substring(string str, int length, int n) takes a string, it’s length, n and returns the count of substrings of str with length n.

• Take a variable count.

• Set count = length-n+1.

• Return count as result at the end.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int possible_substring(string str, int length, int n){
int count = length - n + 1;
return count;
}
int main(){
string str = "learning";
int length = str.length();
int n = 2;
cout<<"Count of substrings of length n possible from the given string are: "<<possible_substring(str, length, n);
return 0;
}

## Output

If we run the above code it will generate the following output −

Count of substrings of length n possible from the given string are: 7