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.

advertisement
advertisement
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

Sanfoundry Global Education & Learning Series – C++ Programs.

To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.

Note: Join free Sanfoundry classes at Telegram or Youtube

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.