Coders Packet

strchr() function in C++

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.

strchr()

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() 

  • str − String in which we have to search the character.
  • cha− Character to be searched in string str.
  • Function strchr()  returns a pointer to the location of the character in str if the character is present else it will return a null pointer.

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 :

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 :

output

 

Download project

Reviews Report

Submitted by Apurv Singh (Apurv)

Download packets of source code on Coders Packet