Caio Pardal
Caio Pardal

Reputation: 53

Program to print all substrings of a given string

I am having trouble creating an algorithm that prints all substrings of a given string. This is my implementation now:

#include <stdio.h>
#include <string.h>

// Function to print all sub strings 
void subString(char str[], int n)  
{ 
    // Pick starting point 
    for (int len = 1; len <= n; len++)  
    {     
        // Pick ending point 
        for (int i = 0; i <= n - len; i++)  
        { 
            //  Print characters from current 
            // starting point to current ending 
            // point.   
            int j = i + len - 1;             
            for (int k = i; k <= j; k++) {
                char data[n];
                sprintf(data, "%d", str[k]);
                printf("%s\n", data);
            }
        } 
    } 
} 

// Driver program to test above function 
int main()  
{ 
    char str[] = "abc"; 
    subString(str, strlen(str)); 
    return 0; 
} 

My code is not converting integers to strings. Could someone help me figure out what's wrong?

Upvotes: 2

Views: 1841

Answers (2)

ani4aniket
ani4aniket

Reputation: 1

#include<bits/stdc++.h>
using namespace std;

int main()
{
    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);    
    string str;
    cin >> str;

    for (int i = 0; i < str.size(); i++) {
        for (int len = 1 ; len <= str.size() - i; len++)
        {
            cout << str.substr(i, len) << endl; // prints substring from starting index i till length len
        }
    }

    return 0;
}

Input:

abcd

Output:

a
ab
abc
abcd
b
bc
bcd
c
cd
d

Upvotes: 0

ggorlen
ggorlen

Reputation: 56965

The logic seems basically fine, but the formatting doesn't make much sense as this prints the digit values for each character and adds a newline for each print call. If you print the characters directly using %c formatting and only print a newline once you've emitted a full substring you'll have a more sensible result.

#include <stdio.h>
#include <string.h>

void subString(char *str, int n)
{ 
    for (int len = 1; len <= n; len++)
    {     
        for (int i = 0; i <= n - len; i++)  
        { 
            for (int j = i; j <= i + len - 1; j++) 
            {
                putchar(str[j]);
            }

            puts("");
        } 
    } 
} 

int main()  
{ 
    char str[] = "abc";
    subString(str, strlen(str)); 
    return 0; 
} 

Output:

a
b
c
ab
bc
abc

A little nitpick: I'd suggest calling this function printSubStrings since it produces a side effect. The name subString doesn't seem to match the contract particularly well.

You can also use the "%.*s" format to extract the substring chunk you want instead of the innermost loop:

void print_substrings(char *str, int n)
{ 
    for (int len = 1; len <= n; len++)
    {     
        for (int i = 0; i <= n - len; i++)  
        {
            printf("%.*s\n", len, str + i);
        }
    } 
} 

Upvotes: 2

Related Questions