C Program to Check Whether a Character is Present in a String

Note: Instead of fgets() you can use gets() function. But it may cause buffer overflow.

Problem:

Write a C program to check if a character is present in the string. Write a C program that will accept a string and a character to search. The program will call a function, which will search for the occurrence position of the character in the string and returns its position. Function should return -1 if the character is not found in the string.

C Program / Source Code:

Here is the source code of C program to check whether a character is present in the string
/* Aim: Write a C program to check the occurrence of a character in a string */

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

int Check_String(char str[],char ch); // Check_String() Function Prototype

void main()
{
 char str[20],ch;

 printf("\n Enter any string (Max 20 characters):- ");
 fgets(str,20,stdin);
 
 printf("\n Enter character to check in the string:-");
 scanf("%c",&ch);

 if(Check_String(str,ch))
 printf("\n First occurrence of %c is at %dth position in --%s \n \n",ch,Check_String(str,ch),str);

} // End of the main

// Check_String() function to find the character

int Check_String(char str[],char ch)
{
 int i;

 for(i=0;i<=strlen(str);i++)
 {
  if(str[i]==ch)
  { 
   return i+1;
  }
 }

 return -1;
}

/* Output of above code:-

[root@localhost Computer Science C]# cc e12a2.c
[root@localhost Computer Science C]# ./a.out

 Enter any string (Max 20 characters):- Hello World

 Enter character to check in the string:-r

 First occurrence of r is at 9th position in --Hello World */