Find first occurrence of a character in the string
C program to find first occurrence of a character in the string.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 50
void main()
{
char str[MAX];
int i, flag;
char ch;
printf("Enter the string\t:");
gets(str);
printf("Enter the character to be searched\t:");
scanf("%c",&ch);
i = 0;
flag = 0;
while(str[i] != '\0')
{
if(str[i] == ch)
{
printf("\nFirst occurrence of the character '%c' is found at position %d",ch,i+1);
flag = 1;
break;
}
i++;
}
if(flag == 0)
{
printf("\nCharacter not found");
}
getch();
}
Output
Enter the string :welcome to coursecrux.com
Enter the character to be searched :c
First occurrence of the character 'c' is found at position 4