strchr() function in C++ and its applications

C++Server Side ProgrammingProgramming

In this article, we will be discussing the working, syntax, and examples of strchr() function in C++ STL.

What is strchr()?

strchr() function is an inbuilt function in C++ STL, which is defined in the <cstring> header file. strchr() function is used to find when the character first occurred in the string. This function returns the pointer to the location where the character first appeared in the string.

If the character doesn’t exist in the string the function returns the null pointer.

Syntax

char* strchr( char* str, char charac );

Parameters

The function accepts the following parameter(s)−

  • str − It is the string in which we have to look for the character.

  • charac − It is the character that we want to search in the string str.

Return value

This function returns a pointer to the location where the character first appeared in the string. If the character is not found it returns the null pointer.

Input

char str[] = "Tutorials Point";
char ch = ‘u’;

Output − u is present in the string.

Example

 Live Demo

#include <iostream>
#include <cstring>
using namespace std;
int main(){
   char str[] = "Tutorials Point";
   char ch_1 = 'b', ch_2 = 'T';
   if (strchr(str, ch_1) != NULL)
      cout << ch_1 << " " << "is present in string" << endl;
   else
      cout << ch_1 << " " << "is not present in string" << endl;
   if (strchr(str, ch_2) != NULL)
      cout << ch_2 << " " << "is present in string" << endl;
   else
      cout << ch_2 << " " << "is not present in string" << endl;
   return 0;
}

Output

b is not present in string
T is present in string

Example

 Live Demo

#include <iostream>
#include <cstring>
using namespace std;
int main(){
   char str[] = "Tutorials Point";
   char str_2[] = " is a learning portal";
   char ch_1 = 'b', ch_2 = 'T';
   if (strchr(str, ch_1) != NULL){
      cout << ch_1 << " " << "is present in string" << endl;
   }
   else{
      cout << ch_1 << " " << "is not present in string" << endl;
   }
   if (strchr(str, ch_2) != NULL){
      cout << ch_2 << " " << "is present in string" << endl;
      strcat(str, str_2);
      cout<<"String after concatenation is : "<<str;
   }
   else{
      cout << ch_2 <<" " << "is not present in string" << endl;
   }
   return 0;
}

Output

b is not present in string
T is present in string
String after concatenation is : Tutorials Point is a learning portal
raja
Published on 22-Apr-2020 14:39:48
Advertisements