Find a specific word in a string in C++

In this tutorial, we will learn how to find a specific word in a string in C++.

Previously, we had found occurrences of a specific word in a string in C++, the link to which is here.

Now, we have to find the specific word, where does it occur and return its position in the string. It will return the first occurrence of the word, from the starting position, we are finding in a string. Starting position in a string is 0.

String find() function is used for this purpose. It will return the index of the first character of the substring we have to find within the string.


Assume we have two strings, s1 being the given string and s2 being the string we have to find.

//if index is not 0
//s1.find(s2, index);

This will return the occurrence of s2 in s1.
For example: s1 = “bagpack”
s2 = “pack”
s1.find(s2) will return index = 3 as pack is found with starting character index equal to 3.

Implementation in C++ Code

#include <bits/stdc++.h>
#include <cstring>
using namespace std;
int main()
    string s1 = "bagpack is pack";
    string s2 = "pack";
    size_t index = s1.find(s2);
    if (index != string::npos)
        cout << "First occurrence is :" << index << endl;
    char a[] = "pack";
    index = s1.find(a, index+1);
        cout<<"Next occurrence is :"<<index<<endl;
    return 0;
First occurrence is : 3
Next occurrence is : 11

Code Explanation

  • Two strings are defined, s1 and s2 as shown in the code above.
  • index is declared as a size_t data type as we need number of bytes of the string to return the index.
  • index is assigned to the find() function.
  • If the string is found in the main string, we return the index it is found at.
  • If not found, it returns string::npos, i.e, no position has been found.
  • To find other occurrences, declare the string again.
  • However, in find() take the position argument as index+1. This is because we are starting the new search from 1st index.
  • Repeat the above steps for finding other indexes and increase index by one in each step.

Leave a Reply

Your email address will not be published.