This blog is under construction

Wednesday 17 July 2013

C program to generate all possible substring of a string

Write a C program to print all possible substrings of a given string.


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

  /* prints num character from the character array ptr */
  void printchar(char *ptr, int num) {
        int i;
        for (i = 0; i < num; i++) {
                printf("%c", *(ptr + i));
        }
        printf("\n");
        return;
  }


  int main() {
        char str[256];
        int i = 0, j;

        /* get the input string from the user */
        printf("Enter your input string:");
        fgets(str, 256, stdin);
        str[strlen(str) - 1] = '\0';

        /* find and print the possible substrings */
        printf("\nPossible Substrings:\n");
        while (str[i] != '\0') {
                /* printing possible substrings */
                for (j = 1; j <= strlen(str) - i; j++) {
                        /* prints j characters from str[i] */
                        printchar((str + i), j);
                }
                i++;
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:India  
  Possible Substrings:
  I
  In
  Ind
  Indi
  India
  n
  nd
  ndi
  ndia
  d
  di
  dia
  i
  ia
  a


3 comments:

  1. It should be str[strlen(str)]='\0';

    ReplyDelete
  2. how do i arrange all these extracted substrings in dictionary order??

    ReplyDelete
    Replies
    1. You can use sort function to sort them which is defined in algorithm liberary

      Delete