OneBite.Dev - Coding blog in a bite size

Find The Index Of A Substring Within A String In C++

Code snippet for how to Find The Index Of A Substring Within A String In C++ with sample and detail explanation

In this article, we will explore how to find the index of a substring within a string using the C++ programming language. This is a common operation and will be useful in a variety of programming scenarios.

Code snippet - Finding the Index of a Substring in C++

Here is a simple code snippet to find the index of a substring within a string:

#include <string>
#include <iostream>

int main()
{
    std::string str = "Hello, this a test message.";
    std::string subStr = "test";

    size_t found = str.find(subStr);

    if (found != std::string::npos)
        std::cout << "The index of '" << subStr << "' is " << found << std::endl;
    else
        std::cout << "The substring is not found." << std::endl;

    return 0;
}

Code Explanation - Finding the Index of a Substring in C++

We start by including the necessary header files, i.e., string (to use the std::string class and its functions) and iostream (for input and output).

#include <string>
#include <iostream>

Next, we define our main function:

int main()

We define two strings str and subStr. str contains the main string in which we want to find the index of the subStr.

std::string str = "Hello, this a test message.";
std::string subStr = "test";

We then attempt to find subStr in str using the find function. The find function will return the index at which the substring starts. If the substring is not found, it will return std::string::npos.

size_t found = str.find(subStr);

A conditional if-else statement then checks the value of found. If found is not equal to std::string::npos, the index of subStr in str is printed. Otherwise, a message is printed stating that the substring is not found.

if (found != std::string::npos)
    std::cout << "The index of '" << subStr << "' is " << found << std::endl;
else
    std::cout << "The substring is not found." << std::endl;

Finally, the main function returns zero and ceases execution of the program.

return 0;
}
c-plus-plus