Print All Substrings of a String
“Print all substrings of a String” is a popular technical interview problem asked in many interviews. Here, we are given a string of length ‘n’ and our task is write a program to count and print all substrings of a string.
Example:
INPUT: ABCD OUTPUT: No of substring: 10 Substrings: A, B, C, D, AB, BC, CD, ABC, BCD, ABCD
The steps required to count and print all substrings of a string are as follows:
- Set count = 0.
- Three nested loops will be taken.
- The outer loop will be used to take the starting character of the substring.
- The middle loop will be used to take the last character of the substring.
- The inner loop will be used to print the substring from starting character (from outer loop) to ending character (from middle loop). Increment count by 1.
C++ Program to count and print all substrings of a string are as follows:
/* C++ Program to count and print all substrings of a string */
#include<bits/stdc++.h>
using namespace std;
int main()
{
string str;
cout<<"Enter a string:\n";
cin>>str;
int count = 0;
cout<<"The substring are:\n";
int size = str.length();
/* Outer loop for starting character of substring */
for(int i = 0; i < size; i++)
{
/* Middle loop for ending character of substring */
for(int j = i; j < size; j++)
{
string substring = "";
/* Inner loop for creating substring */
for(int k = i; k <= j; k++)
{
substring = substring + str[k];
}
count++;
cout<<substring<<"\n";
}
}
cout<<"The number of substrings are "<<count;
}
OUTPUT: Enter a string: ABCD The substring are: A AB ABC ABCD B BC BCD C CD D The number of substrings are 10 Time Complexity: O(n^3), where n is the length of the string
Related Posts:
- Program to find longest palindromic Substring.
- Program to check Anagram Strings.
- Program to check whether two Strings are Rotation of each other or not.
- Program to check Palindromic Anagram.
- Program to print all the Palindromic Substring of the String.
- Program to check Panagram String.
- Program to find first non-repeating character of the String.
- Program to print all possible subarrays of the given array.
- Program to print kth smallest and kth largest element of an Array.
- Program to find equilibrium index of an Array.
- Program to find majority element of an Array.
- Program to find mean of the Array.
- Program to sort an Array of 0s and 1s.
- Program to find first repeating element of an array.
- Program to merge two sorted arrays.
- Program to find missing number in an array.
- Program to sort if array is sorted.
- Program to print Alternate Elements of an Array.
- Program to swap kth element from beginning to kth element from end in an Array.
- Program to print all possible subarrays of the given array.