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.  */
  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. }

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.

Note: Join free Sanfoundry classes at Telegram or Youtube
If you wish to look at all C++ Programming examples, go to C++ Programs.

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 & technical discussions at Telegram SanfoundryClasses.