Locate a character in String – STRCHR

Locate a character in String - STRCHR

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn C programming concepts. You can learn C language at your own speed and time. One can learn concepts of C language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Locate a character in String - STRCHR
Locate a character in String – STRCHR

Write a C program to Locate a character in String – STRCHR

PROGRAM: Locate a character in String – STRCHR

/* Locate a character in String - STRCHR */

#include<stdio.h>

int main()
{
 char str[500];
 int i;
 char ch;
 printf("Please enter your string: ");
 // gets(str); 
 // fgets is a better option over gets to read multiword string .
 fgets(str, 500, stdin);
 // Following can be added for extra precaution for '\n' character
 // if(str[length(str)-1] == '\n') str[strlen(str)-1]=NULL;

 printf("Please enter a character: ");
 getchar(ch); 
 
 for(i=0;str[i]!=NULL;i++)
 {
  if(str[i]==ch)
   break;
 }
 
 if(str[i] == NULL)
  printf("%c not found in %s",ch,str);
 else
  printf("\"%c\" found in \"%s\" at %d location",ch,str,i+1);

 return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *