This is a C++ Program to Implement the strchr() Function.
The program implements the function strchr() which takes a string and a character and returns a pointer to location of the latter in the string.
1. The program takes a string and a character.
2. Using a for loop, the character is compared with the string.
3. If found, position is stored and printed. Else it returns NULL.
4. The result is printed.
Here is the source code of C++ Program to Implement the strchr() Function. The program output is shown below.
using namespace std;
int main ()
char str, ch;
int i, pos = 0;
cout << "Enter a string : ";
cout << "Enter a character : ";
cin >> ch;
for (i = 0 ; str[i] != '\0'; i++)
if (str[i] == ch)
pos = i;
cout << ch << " found at position : " << pos + 1;
cout << ch << " not found.";
1. The user is asked to enter a string, which is stored in ‘str’.
2. The character to be searched is asked to enter and stored in ‘ch’.
3. Using a for loop, the string is checked if the character is present.
4. If found, the position of the character in the string is stored in the variable ‘pos’.
5. If pos is not 0, the resultant position is printed.
6. Else NULL is returned.
Case 1 : Enter a string : West Enter the character : w w not found. Case 2 : Enter a string : Odd Elements Enter the character : e e found at position : 7 Case 3 : Enter a string : november Enter the character : m m found at position : 5
Sanfoundry Global Education & Learning Series – C++ Programs.
To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.