Program to search for a character in a string


C File =>



/* Write a C program that accepts a string and character to search. The program will call a function, which will search for the position of occurrence of the character in the string and return its position. Function should return –1 if the character is not found in the string.*/

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


int main()
{
     char s[50];
     char ch;
     int pos;
     printf("\n Enter String : ");
     scanf("%s",s);
     printf("\n Enter character to search : ");
     scanf("%c",&ch);
     int search(char str[50],char ch)
    {
         int i,flag=0;
         for(i=0;i<strlen(str);i++)
        {
            if(str[i]==ch)
           {
               flag=1;
               break;
            }
        }
        if(flag==1)
           return i+1;
        else
           return -1;
     }
//Calling function
   pos=search(s,ch);
   if(pos==-1)
     printf("\n %c not found in %s",ch,s);
  else
     printf("\n %c found in %s at position %d",ch,s,pos);
  return 0;
}

Comments

Popular posts from this blog

Write a program to allocate memory dynamically for n integers. Accept the elements and calculate their sum and average

C program to accept names of n cities and search for city named “Pune”.