Register | Sing In

New posts

Stacks in C programming Linked Lists in C programming File Input/Output in C programming Check prime numbers in C Programming C Programming Enumeration C Programming Union

Archives

2013-10 2013-09 2013-08

Function strchr in C programming

September 13, 2013 Posted by: GPA Views: 658 0 comments

Problem

Check if a character exists in a char array using function strchr() in C programming.

Solution

In this section, you will get the detailed explanation about the strchr() method of header file <string.h>.

Declaration:

char *strchr( const char *str, int c );

This function strchr searches for the first occurrence of a character in a char array. If the character is found, it returns a pointer to the character in the string; otherwise, it returns NULL. 

In this example we prompt the user to enter string and character for searching.  

Example:




#include <stdio.h>
#include <stdlib.h>
#include <string.h>//include this header file for function strchr
int main(int argc, char *argv[])
{
char* inputstring;//variable for input string
char searchCharacter;//variable for searching char
printf("globalproganswer.com\n");
printf("Enter string: ");//promt user to enter some string
scanf("%s",&inputstring);//read string from keyboard
printf("What character do you want to search: ");//promt user to enter some character
//read character
searchCharacter=getchar();
searchCharacter=getchar();
//call function strchr
if (strchr(&inputstring, searchCharacter ) != NULL ){
//show result found
printf( "\'%c\' was found in \"%s\".\n", searchCharacter,&inputstring );
} else {
//show result not found
printf( "\'%c\' was not found in \"%s\".\n",searchCharacter,&inputstring);
}

printf("\n");//new line
system("PAUSE"); //delay
return 0;
}

Output

Function strchr

Download this example

0 Comments...

Leave a Reply

Please, Sing In to leave a Reply for this material.



Online Chat

LiveZilla Live Help

Popular posts

Function strtok in C programming Check prime numbers in C Programming C Programming Union Linked Lists in C programming File Input/Output in C programming C Programming Enumeration

RSS-subscribe

New materials

Subscribe