Implement String Matching Using Vectors in C++



In C++, we can create vectors easily using the standard library. We are taking the main string and the string that will be searched as a vector, then searching it into the main string. When one match is found the function returns the address, and removes it from the main string. So in the next iteration, it starts from location 0 and searches again.

For multiple occurrences, we are using loops and repeatedly searching for the match, and return the position.

Input:
Main String: "ABCcdABCcdABC"
Substring to search: "cd"

Output:
Match found at Position = 1
Match found at Position = 5

Algorithm

vector_pattern_search(main, substr)

Input ? The main text and the substring.

Output ? location where patterns are found

Begin
p := starting point of the main string
while r is not at the end of substr and p is not at the end of main, do
    r := starting of substr
    while item at position p & r are not same, and p in main, do
        p := p + 1
        i := i + 1
    done
    q := p
    while item at pos p & r are same, and r in substr and p in main, do
        p := p + 1
        i := i + 1
        r := r + 1
    done
    if r exceeds the substr, then
        delete first occurrence of substr from main
        return the position where substr is found

    if p exceeds main string, then
        return 0
        q := q + 1
        p := q
done
End

C++ Program to Implement String Matching Using Vectors

In the code below, we will take a main string and a substring to search for. The program will then find all occurrences of the substring in the main string and display their positions:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
    string mainStr = "ABCcdABCcdABC";
    string subStr = "cd";
    vector<int> positions;
    size_t pos = 0;

    while ((pos = mainStr.find(subStr, pos)) != string::npos) {
        positions.push_back(static_cast<int>(pos) + 1); // 1-based index
        pos += 1; // Move to next character for next search
    }

    for (int p : positions) {
        cout << "Match found at Position = " << p << endl;
    }

    return 0;
}

The output of the above code will be:

Match found at Position = 4
Match found at Position = 9
Farhan Muhamed
Farhan Muhamed

No Code Developer

Updated on: 2025-06-04T16:25:31+05:30

590 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements