C++ program to print all possible substrings of a given string
#include <iostream>
using namespace std;
void printSubstrings(string str) {
int n = str.length();
for (int len = 1; len <= n; len++) {
for (int start = 0; start <= n - len; start++) {
int end = start + len - 1;
for (int i = start; i <= end; i++) {
cout << str[i];
}
cout << endl;
}
}
}
int main() {
string input;
cout << "Enter a string: ";
cin >> input;
cout << "All substrings of \"" << input << "\" are:" << endl;
printSubstrings(input);
return 0;
}
This C++ program defines a function printSubstrings
that takes a string str
as input and prints all possible substrings of that string. It uses nested loops to generate substrings of different lengths by iterating through the string and printing each substring. The main
function reads a string from the user, calls printSubstrings
, and displays all the substrings of the input string.