How to print all substrings of a given string in C++

1 Answer

0 votes
#include <iostream>

void print_substrings(std::string str) {
    for(int i = 0; i < str.length(); i++) {
        for(int j = 1; j <= str.length() - i; j++) {
            std::string s(str, i, j); 
            std::cout << s << "\n";
        }
    }
}
 
int main()
{
    std::string str = "abcd";
    
    print_substrings(str);
    
    return 0;
}




/*
run:
 
a
ab
abc
abcd
b
bc
bcd
c
cd
d
 
*/

 



answered Sep 5, 2021 by avibootz
edited Sep 5, 2021 by avibootz
...