
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
C++ Program to Implement the String Search Algorithm for Short Text Sizes
In this C++ program, as input, a text and a pattern are given. As output, the pattern is searched in the text and all instances of the pattern are given.
Algorithm
Begin Take the string and pattern as input. Declare the original and duplicate array with their size. Put the lengths of original and duplicate in len_ori and len_dupli. Make a loop for find out the position of the searched pattern. If pattern is not found, print not found otherwise print the no of instances of the searched pattern. End
Example Code
#include<iostream> #include<cstring> using namespace std; int main() { char ori[120], dupli[120]; int i, j, k = 0, len_ori, len_dupli; cout<<"enter string without any blank space"<<endl; cout<<"\nEnter Original String:"; cin>>ori; cout<<"Enter Pattern to Search:"; cin>>dupli; len_ori = strlen(ori); len_dupli = strlen(dupli); for (i = 0; i <= (len_ori - len_dupli); i++) // loop to find out the position Of searched pattern { for (j = 0; j < len_dupli; j++) { if (ori[i + j] != dupli[j]) break ; } if (j == len_dupli) { k++; cout<<"\nPattern Found at Position: "<<i; } } if (k == 0) cout<<"\nNo Match Found!"; else cout<<"\nTotal Instances Found = "<<k; return 0; }
Output
enter string without any blank space Enter Original String:Enter Pattern to Search: Pattern Found at Position: 0 Pattern Found at Position: 1 Pattern Found at Position: 2 Pattern Found at Position: 3 Total Instances Found = 4
- Related Articles
- C++ Program to Implement Interpolation Search Algorithm
- C++ Program to Implement a Binary Search Algorithm for a Specific Search Sequence
- C++ Program to Implement Bitap Algorithm for String Matching
- Swift Program to Implement Binary Search Algorithm
- Swift Program to Implement Linear Search Algorithm
- C++ Program to Implement Wagner and Fisher Algorithm for online String Matching
- C++ Program to Implement the RSA Algorithm
- C++ Program to Implement Kadane’s Algorithm
- C++ Program to Implement Johnson’s Algorithm
- C++ Program to Implement Fisher-Yates Algorithm for Array Shuffling
- C++ Program to Implement The Edmonds-Karp Algorithm
- C++ Program to Implement the Bin Packing Algorithm
- C++ Program to Implement Nearest Neighbour Algorithm
- C++ Program to Implement Expression Tree Algorithm
- C++ Program to Implement Extended Euclidean Algorithm

Advertisements