C++ Standard Library C++ STL Library

C++ <cstring> - strchr() Function



The C++ <cstring> strchr() function is used to find the first occurrence of character in the byte string pointed to by str. The terminating null character is considered as a part of the string and can be found if searching for '\0'.

The function returns pointer to the first occurrence of character in str, or null pointer if character is not found in str.

Syntax

const char * strchr ( const char * str, int character );
char * strchr ( char * str, int character );                

Parameters

str Specify pointer to the null-terminated byte string to be searched in.
character Specify the character to searched for.

Return Value

Returns pointer to the first occurrence of character in str, or null pointer if character is not found in str.

Example:

The example below shows the usage of strchr() function.

#include <iostream>
#include <cstring>
using namespace std;
 
int main (){
  char MyStr[100] = "To be, or not to be, that is the question.";
  char * search;
  
  //searching for all occurrences of 'o' in MyStr
  cout<<"Searching for all occurrences of 'o' in MyStr.\n";
  search = strchr(MyStr, 'o');

  //displaying the result
  while(search != NULL) {
    cout<<"Found at: "<<(search-MyStr+1);
    cout<<endl;
    search = strchr(search+1, 'o');
  }
 
  return 0;
}

The output of the above code will be:

Searching for all occurrences of 'o' in MyStr.
Found at: 2
Found at: 8
Found at: 12
Found at: 16
Found at: 40

❮ C++ <cstring> Library