By Apurv Singh
In this tutorial, we will learn about strchr() function in C++. It is a predefined function and is present in the cstring header file.
Definition of strchr()
The strchr() is an inbuilt function in C++ STL, strchr() function is used to search for the first occurrence of a character in a string. This function returns a pointer to the first occurrence of the character in the string.
The function returns a null pointer if it does not get the character in the string.
The syntax of this function is as follows:
const char* strchr( const char* str, int cha); char* strchr( char* str, int cha );
Parameters of strchr()
We need to pass the string in the strchr() function and indicate the character to be printed and then functions return a value to be printed. Let’s have a look at the following program to understand the working of strchr() function :
#include <bits/stdc++.h> using namespace std; int main() { char str[] = "This is a packet"; char* cha = strchr(str, 'c'); cout <<"Position of c in string is"<<" "<< cha - str + 1; return 0; }
Output :
The strchr() function can also be used to check the existence of a character in a string.
For example – Let's check whether the characters T and f are present in the string – "This is a packet".
#include <bits/stdc++.h> using namespace std; int main() { char str[] = "This is a packet"; char cha1 = 'T', cha2 = 'f'; if (strchr(str, cha1) != NULL) cout << cha1 << " " << "is present in string" << endl; else cout << cha1 << " "<< "is not present in string" << endl; if (strchr(str, cha2) != NULL) cout << cha2 << " " << "is present in string" << endl; else cout << cha2 << " "<< "is not present in string" << endl; return 0; }
Output :
Submitted by Apurv Singh (Apurv)
Download packets of source code on Coders Packet
Comments