Search all occurrences of a word in a string
C program to search all occurrences of a word in given string.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 50
int split_words(char str[MAX], char words[MAX][MAX])
{
int i, j, count;
char prev_char;
i = 0;
j = 0;
count = 0;
prev_char = '\0';
while(1)
{
if(str[i] == ' ' || str[i] == '\t' || str[i] == '\0')
{
if(prev_char!=' ' && prev_char!='\t' && prev_char!='\0')
{
words[count][j] = '\0';
count++;
j = 0;
}
}
else
{
words[count][j] = str[i];
j++;
}
prev_char = str[i];
if(str[i] == '\0')
break;
else
i++;
}
return(count);
}
void main()
{
char str[MAX], word[MAX];
char words[MAX][MAX];
int count, i, flag, index, index1;
printf("Enter the string\t:");
gets(str);
printf("Enter the word to be searched\t:");
gets(word);
count = split_words(str, words);
flag = 0;
index = 0;
index1 = 0;
for(i=0;i<count;i++)
{
if(!strcmp(words[i],word))
{
flag = 1;
index1 = index;
printf("\nWord '%s' found at position %d",word,index1+1);
}
index = index + strlen(words[i]) + 1;
}
if(flag==0)
{
printf("\nWord not found");
}
getch();
}
Output
Enter the string :welcome to coursecrux, welcome to c
Enter the word to be searched :welcome
Word 'welcome' found at position 1
Word 'welcome' found at position 24