C++ Program to Perform String Matching using String Library

This C++ program performs string matching using string library of C++. A text and a pattern is given as input. The pattern is searched for in the text and all instances of the pattern are given as output.

This C++ program is successfully compiled and tested on our system. The program output is given below.

  1. /*
  2.  * C++ Program to Perform String Matching Using String Library
  3.  */
  4.  
  5. #include <iostream>
  6. #include <string>
  7. using namespace std;
  8. int main()
  9. {
  10.     std::string org, dup;
  11.     int result = -1, i = 1;
  12.     std::cout<<"Enter Original String:";
  13.     getline(std::cin, org);
  14.     std::cout<<"Enter Pattern String:";
  15.     getline(std::cin, dup);
  16.     do
  17.     {
  18.         result = org.find(dup, result + 1);
  19.         if (result != -1)
  20.             std::cout<<"\nInstance:"<<i<<"\tPosition:"<<result<<"\t";
  21.         i++;
  22.     } while (result >= 0);
  23.     return 0;
  24. }

Output
 
Enter Original String:All men went to the appall mall
Enter Pattern String:all
 
Instance:1      Position:23
Instance:2      Position:28

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

advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification 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
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.