Print subtrings recursively

Asked

Viewed 45 times

-3

I need to print substrings for a string, for example: OPEN, substrings are OPEN, OPEN, ABR, AB, A. How do I do this? 'Cause all I’m doing is printing the whole string.

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

void subtring(char *ch, int size, int aux) {
    if (size > 0) {
        subtring(ch, size - 1);
        printf("%c", ch[size - 1]);
    }
}

int main(int argc, char const *argv[]) {
  char ch[100];

   printf("Digite uma palavra -> ");
   gets(ch);

   int size = strlen(ch);

   subtring(ch, size);

   return 0;

}
  • 1

    What is the doubt?

  • @Marcelouchimura how do I print these subtrings, because I can only print the entire string

2 answers

1

#include <stdio.h>
#include <stdlib.h>

char* substr(char* stringOriginal) {
    char *p;
    char *s;

    p = stringOriginal + 1;

    if (!*stringOriginal || !*p) return 0;

    s = substr(p);

    if (s) 
    {
        printf("%s\n", s);
    }

    return p;
}

int main(int argc, char* argv[]) 
{
    char palavra[80];

    printf("Digite a palavra: ");

    fgets(palavra, 80, stdin);

    printf("%s\n", palavra);

    substr(palavra);

    return 0;
}

0


Follow the desired code:

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

typedef char string[100];

void substrings(string str) {
    if (strlen(str) >= 1) {
        puts(str);
        substrings(str + 1);
    }
}

void todas_substrings(string str) {
    int tam = strlen(str);

    if(tam >= 1) {
        substrings(str);
        str[tam - 1] = '\0';
        todas_substrings(str);
    }
}

int main(int argc, char const *argv[]) {
    string str = "UTFPR";
    todas_substrings(str);
    return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.