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;
}
#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
Enter your input string:India
Possible Substrings:
I
In
Ind
Indi
India
n
nd
ndi
ndia
d
di
dia
i
ia
a
It should be str[strlen(str)]='\0';
ReplyDeletehow do i arrange all these extracted substrings in dictionary order??
ReplyDeleteYou can use sort function to sort them which is defined in algorithm liberary
Delete