Write a program that checks whether a given substring is present in the given string.
Example
Enter the string : my name is toto
Input the substring : to
The substring exists in the string at position 12.
Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#define SIZE 100
void main()
{
char str[SIZE], substr[SIZE];
int i,j,flag;
printf("Enter the string : ");
gets(str);
printf("Input the substring : ");
gets(substr);
for(i=0; str[i]!='\0'; i++)
{
flag=1;
for(j=0; substr[j]!='\0';j++)
{
if (str[i+j]!=substr[j])
{
flag=0;
break;
}
}
if (flag==1)
break;
}
if (flag==1)
printf("The substring exists in the string at position %d.\n", i+1);
else
printf("The substring does not exists in the string.\n");
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Implementation of a deque using a doubly-linked list