Write a program that reads two strings s1 and s2, and then prints on the screen the number of times s1 appears in s2, and the position of each occurrence of s1 in s2.
Difficulty level
Video recording
This exercise is mostly suitable for students
#include <stdio.h>
#include <string.h>
#define size 200
int main()
{
char s1[size], s2[size];
int i, j , k, nb;
printf("Enter a first string: ");
gets(s1);
printf("Enter a second string: ");
gets(s2);
i=0;
nb=0;
while(s2[i])
{
j=0;
k=i;
while(s2[k] && s1[j] && s1[j] == s2[k])
{
j++;
k++;
}
if(s1[j]=='\0')
{
printf("s1 found in s2 at position %d\n", i);
nb++;
i = i+j-1;
}
if(s2[k])
i++;
if(!s2[k])
break;
}
printf("Nb of occurrence = %d\n", nb);
return 0;
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Automata