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
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.
5. Exit.
Here is the source code of C++ Program to Implement the strchr() Function. The program output is shown below.
#include<iostream>
#include<iostream>
#include<string.h>
#include <cstring>
using namespace std;
int main ()
{
char str[50], ch;
int i, pos = 0;
cout << "Enter a string : ";
gets(str);
cout << "Enter a character : ";
cin >> ch;
for (i = 0 ; str[i] != '\0'; i++)
if (str[i] == ch)
pos = i;
if (pos)
cout << ch << " found at position : " << pos + 1;
else
{
cout << ch << " not found.";
return NULL;
}
return 0;
}
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