In this tutorial you will learn about the C Program to Find First Occurrence of a Word in a String and its application with practical example.
C Program to Find First Occurrence of a Word in a String
In this tutorial, we will learn to create a C program that will Find the First Occurrence of a Word in a String in C programming
Before starting with this tutorial we assume that you are best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- For loop in C programming.
- Conditional Statements in C programming.
What is a string?
As we all know the String is a collection of characters and words. The word is a collection of alphabets. For string, only one variable is declared which can store multiple values. The String can consist of all the typeable data it means Digits, Alphabets, Symbols, etc.
1. Declaring the variables for the program.
2. Taking the input string from the user.
3. Taking the input from user the word needs to be searched.
4. Passing those variables to for loop.
5. Using conditional statements for the program to find the first occerence of word.
6. Printing the result position.
7. End the program.
Find the First Occurrence of a Word in a String
In this program first, we will take input string from the user. Then we will take the word to be searched from the user. Then will find the first occurrence of that word in that string. Printing the position of that word.
Let us take the example program from the below code to search for the first occurrence of that word.
/* C Program to Find First Occurrence of a Word in a String */
//declaring the required variables for the program
char str, word;
int i, j, Flag;
//Taking input string from the user
printf("\n Please Enter any String : ");
//taking the input word to look into the string
printf("\n Please Enter the Word that you want to Search for : ");
//Finding that word in the string
for(i = 0; str[i] != '\0'; i++)
if(str[i] == word)
Flag = 1;
for(j = 0; word[j] != '\0'; j++)
if(str[i + j] != word[j])
Flag = 0;
if(Flag == 1)
if(Flag == 0)
//printing the output result if not found.
printf("\n Sorry!! We haven't found the Word '%s' ", word);
//printing the output result if found.
printf("\n We found '%s' at position %d ", word, i + 1);
In the above program, we have first initialized the required variable.
- strg = it will hold the string value.
- word = it will hold the string value.
- j = it will hold the integer value.
- i = it will hold the integer value.
- flag = it will hold the integer value
Input string from the user for the program and Take the input Word from the user to search.
Searching the word in the string.
Printing output position of the word.