OneBite.Dev - Coding blog in a bite size

Find The Position Of The First Occurrence Of A Substring In A String In C++

Code snippet for how to Find The Position Of The First Occurrence Of A Substring In A String In C++ with sample and detail explanation

In programming, it’s often beneficial to be able to locate the position of a specific substring within a larger string. This task can be achieved quite simply in C++ and will be the focus of our discussion.

Code Snippet: Finding First Occurrence of a Substring in a String

#include<iostream>
#include<string>

int main() {
  std::string main_str = "Hello, welcome to the world of C++ programming.";
  std::string sub_str = "world";
  
  std::size_t pos = main_str.find(sub_str);
  
  if(pos != std::string::npos) 
    std::cout << "Found at position: " << pos << '\n';
  else 
    std::cout << "Not found\n";

  return 0;
}

Code Explanation: Finding First Occurrence of a Substring in a String

At first step, we’re including the necessary header files - iostream for input and output operations and string because we’re working with strings.

In the main() function, we are declaring two std::string variables main_str and sub_str. main_str contains the main string and sub_str contains the substring that we’re going to find within main_str.

Next, we’re using the find function, which is a member function of the std::string class. This function returns the first occurrence of the substring in the main string. If the substring is not present, it returns a constant std::string::npos.

We’re storing the return value of find in a variable pos of type std::size_t.

Then we’re using if statement to check whether pos is equal to std::string::npos or not. If pos equals std::string::npos, it means the substring wasn’t found and we print “Not found”. If not, it means the substring was found and we print the position stored in the pos.

Keep in mind though, this code will provide the first occurrence of the substring. If the substring appears multiple times, this will not be reflected in the output.

This basic handling of strings is a stepping stone towards more complex string manipulations in C++.

c-plus-plus