strchr() function in C++

4

strchr() function
In C++, strchr() is a predefined function used for string handling. cstring is the header file required for string functions.

This function Returns a pointer to the last occurrence of a character in a string.
The character whose last occurrence we want to find in passed as the second argument to the function and the string in which we have to find the character is passed as the first argument to the function.
Syntax

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

Here, str is the string and c is the character to be located. It is passed as its int promotion, but it is internally converted back to char.
Application
Given a string in C++, we need to find the last occurrence of a character, lets say ‘a’.

Examples:

Input : string = 'This is a string'
Output :9

Input :string = 'My name is Ayush'
Output :12

Algorithm
1. Pass the given string in the strchr() function and mention the character you need to point.
3. The function return a value,print the value.

// C++ program to demonstrate working strchr()
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
  char str[] = "This is a string";
  char * ch = strrchr(str,'a');
  cout << ch - str + 1;
  return 0;
}

Output:

9

This article is contributed by Ayush Saxena. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



4 Average Difficulty : 4/5.0
Based on 1 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.