strchr() Function in C++


In C++, strchr() is a predefined function. It is used for string handling and it returns the first occurance of a given character in the string provided.

The syntax of strchr() is given as follows.

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

In the above syntax, str is the string that contains the character c. The strchr() function finds the first occurrence of c in str.

A program that demonstrates the strchr() function is given as follows.

Example

 Live Demo

#include <iostream>
#include <cstring>
using namespace std;
int main() {
   char str[] = "strings";
   char * c = strchr(str,'s');
   cout << "First occurrence of character "<< *c <<" in the string is at position "<< c - str + 1;
   return 0;
}

Output

First occurrence of character s in the string is at position 1

In the above program, first the string str is defined. Then pointer c points to the first occurrence of character s in the given string. This is obtained using strchr(). The position of s is displayed using cout. All this is given in the following code snippet.

char str[] = "strings";
char * c = strchr(str,'s');
cout << "First occurrence of character "<< *c <<" in the string is at position "<< c - str + 1;

The strchr() function can also be used to display the string after the first occurance of a particular character i.e it can display the suffix of the string. A program demonstrating this is as follows.

Example

 Live Demo

#include <iostream>
#include <cstring>
using namespace std;
int main() {
   char str[] = "strings";
   char * c = strchr(str,'i');
   cout << "Remaining string after first occurance of "<< *c <<" is "<< c ;
   return 0;
}

Output

Remaining string after first occurance of i is ings

In the above program, first the string str is defined. Then pointer c points to the first occurrence of character s in the given string. This is obtained using strchr(). The rest of the string from the position pointed to by c is printed using cout. All this is given in the following code snippet.

char str[] = "strings";
char * c = strchr(str,'i');
cout << "Remaining string after first occurance of "<< *c <<" is "<< c ;

Updated on: 24-Jun-2020

298 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements