Write a C program to check sub string in a string.
#include <string.h>
int main() {
char str[256], substr[128];
int i = 0, j = 0, flag = 0;
/* get the input string from the user */
printf("Enter your input string:\n");
fgets(str, 256, stdin);
/* get the substring from the user */
printf("Enter your substring:\n");
fgets(substr, 128, stdin);
str[strlen(str) - 1] = '\0';
substr[strlen(substr) - 1] = '\0';
/* check whether substring is present in input string "str"*/
while (str[i] != '\0') {
if (str[i] == substr[j]) {
j++;
if (substr[j] == '\0')
break;
flag = 1;
} else {
flag = 0;
j = 0;
}
i++;
}
/* print the result */
if (substr[j] == '\0' && flag)
printf("%s is the substring of %s\n", substr, str);
else
printf("%s is not a substring of %s\n", substr, str);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your input string: Helloworld
Enter your substring: llowor
llowor is the substring of Helloworld
Enter your input string: Helloworld
Enter your substring: llowor
llowor is the substring of Helloworld
No comments:
Post a Comment