Quantcast
Channel: Codeforwin
Viewing all articles
Browse latest Browse all 132

C program to find first occurrence of a word in a string

$
0
0
Write a C program to read a string from user and find the first occurrence of word in a given string. How to find the first occurrence of a word in a given string in C. How to check whether a string exists in a given string.

Example:
Input string: I love programming.
Input word: love
Output: love is present at 3.

Required knowledge

Basic C programming, Loop, String

Program


/**
* C program to find the first occurrence of a word in a string
*/

#include <stdio.h>
#include <string.h>

int main()
{
char text[100], word[20];
int pos, i, found = 0;

/*
* Reads a string from user and word to be searched
*/
printf("Enter any string: ");
gets(text);
printf("Enter character to be searched: ");
gets(word);

/*
* Searches in the string word by word
*/
pos = 0;
while(text[pos] != '\0')
{
/*
* If first character matches with the given string
*/
if(text[pos]==word[0])
{
/*
* Match entire word with current found index
*/
i=0;
found = 1;
while(word[i]!='\0')
{
if(text[pos+i] != word[i])
{
found = 0;
break;
}

i++;
}
}

/* If the word is found then get out of loop */
if(found == 1)
{
break;
}
pos++;
}

/*
* If the word is found print success message
*/
if(found == 1)
{
printf("\"%s\" is found in string \"%s\" at %d position.", word, text, (pos+1));
}
else
{
printf("\"%s\" is not found in string \"%s\"", word, text);
}

return 0;
}



Note:\" is an escape sequence character used to print ".


Output
X
_
Enter any string: I love programming.
Enter character to be searched: love
"love" is found in string "I love programming." at 3 position.

Happy coding ;)



Viewing all articles
Browse latest Browse all 132

Trending Articles