C++ Program to Implement strchr() Function
Posted by Superadmin on August 10 2022 13:16:25

C++ Program to Implement strchr() Function

 

 

This is a C++ Program to Implement the strchr() Function.

Problem Description

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.

Problem Solution

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.

C++ Program/Source code

Here is the source code of C++ Program to Implement the strchr() Function. The program output is shown below.

  1. #include<iostream>
  2. #include<iostream>
  3. #include<string.h>
  4. #include <cstring>
  5. using namespace std;
  6. int main ()
  7. {
  8.     char str[50], ch;
  9.     int i, pos = 0;
  10.     cout << "Enter a string  : ";
  11.     gets(str);
  12.     cout << "Enter a character : ";
  13.     cin >> ch;
  14.     for (i = 0 ; str[i] != '\0'; i++)
  15.         if (str[i] == ch)
  16.                 pos = i;
  17.     if (pos)
  18.         cout << ch << " found at position : " << pos + 1;
  19.     else
  20.     {
  21.         cout << ch << " not found.";
  22.         return NULL;
  23.     }			
  24.     return 0;
  25. }
Program Explanation

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.

 
Runtime Test Cases
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