String Matching Using String Library in C++



The string library provides several functions to manipulate and match strings. In this article, we will see how the various functions of string library functions can be used to match strings in C++.

String Matching in C++

String matching is a process of locating one string in another string. Meaning, here we will find the position of a string inside another string. The string matching functions will return the position of the first occurrence of the substring in the main string. If the substring is not found, it will return a special value such as -1 or string::npos.

For example, the code below shows how string matching works:

// Input strings
Main String: "Hello, welcome to the world of C++ programming."
Substring: "C++""

// Output
Position of substring: 30

String Matching Functions in C++

As discussed above, the string library in C++ provide several inbuilt function to perform string matching. Here are some of the commonly used functions:

  • find(): The find() function searches for the first occurrence of a substring inside the main string and returns its position.
  • rfind(): The rfind() function searches for the last occurrence of a substring inside the main string and returns its position.
  • substr(): The substr() function will extract a substring from a string.
  • compare(): The compare() function will compare two strings or substrings.

C++ Program for String Matching using String Library

In the below code, we demonstrate how to use the find() function to check for the presence of a substring in a given string.

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

int main() {
    string text = "Hello world, welcome to TutorialsPoint!";
    string pattern = "world";

    // Find the position of the substring
    size_t position = text.find(pattern);

    if (position != string::npos) {
        cout << "Substring found at position: " << position << endl;
    } else {
        cout << "Substring not found." << endl;
    }

    return 0;
}

The output of above code will be:

Substring found at position: 6

Time and Space Complexity

Time Complexity: O(n), where n is the length of the main string.

Space Complexity: O(1), as no extra space.

Updated on: 2025-05-26T12:47:32+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements