strstr() function in C++

In this guide, you will learn what is strstr() function is in C++ programming and how to use it with an example.

1. strstr() Function Overview

The strstr() function is part of the <cstring> library in C++. It searches for the first occurrence of a substring (substr) in a main string (str). If the substring is found, it returns a pointer to the beginning of the located substring, or otherwise returns a null pointer.

Signature:

const char* strstr(const char* str, const char* substr);

Parameters:

- str: The main string where the search is performed.

- substr: The substring to be searched for in str.

2. Source Code Example

#include <iostream>
#include <cstring>

int main() {
    const char* string = "Hello, World!";
    const char* substring_to_find = "World";

    const char* result = strstr(string, substring_to_find);

    if(result) {
        std::cout << "Substring found at position: " << (result - string) << std::endl;
    } else {
        std::cout << "Substring not found in the main string." << std::endl;
    }

    return 0;
}

Output:

Substring found at position: 7

3. Explanation

1. We've included the <iostream> header for standard input/output and <cstring> for the strstr() function.

2. We initialize two strings: string and substring_to_find. Our goal is to determine if substring_to_find is present in string.

3. We then use the strstr() function to get a pointer to the beginning of the located substring.

4. Depending on whether the substring is found or not, we display the appropriate result.

The strstr() function is beneficial when you want to check if one string is present within another string.


Comments