C Program to Find first occurrence of char from a String.

C Program to Find first occurrence of char from a String.Compiled in DEV C++

 

#include<stdio.h>
#include<string.h>
#include<conio.h>
int First_Occurrence_Char(char [],char );
main()
{
      char text[30],searchChar;
      int position;
      
       printf("\nProgram to Find first occurrence of char from a String \n");
       printf("\n-----------------------------------------------------------\n\n\n");
       printf("Enter Text : ");                                                   
       gets(text);
       
       printf("\nSearched Char : ");
       scanf("%c",&searchChar);
       
       position=First_Occurrence_Char(text,searchChar);
      
       printf("\nCharecter '%c' Found in String '%s' at Position %d",searchChar,text,position);
       
       
       getch();
       
} 
      
           
int First_Occurrence_Char(char a[],char b)

{
     
     int i;
     char *p;
     
     for(i=0;i<strlen(a);i++) 
     {
         p=&a[i];       
      
        
         
         if(*p==b)
         {
                  
                    break;
                 
         }
               
                              
     }    
     if(i==strlen(a))
     {
       return -1;                
     }
     else
     {
         return i;
     }
     
}

Output

occurrence

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s