Check if a string contains a sub-string in C++

C++Server Side ProgrammingProgramming

Here we will see how the string library functions can be used to match strings in C++. Here we are using the find() operation to get the occurrences of the substring into the main string. This find() method returns the first location where the string is found. Here we are using this find() function multiple times to get all of the matches.

If the item is found, this function returns the position. But if it is not found, it will return string::npos.

So for checking whether the substring is present into the main string, we have to check the return value of find() is string::npos or not.

Here we are simply getting the position where the substring is present.

Input: The main string “aabbabababbbaabb” and substring “abb”
Output: The locations where the substrings are found. [1, 8, 13]


String_Find(main_str, sub_str)

Input − The main string and the substring to check

Output − The positions of the substring in the main string

pos := 0
while index = first occurrence of sub_str into the str in range pos to end of the string, do
   print the index as there is a match
   pos := index + 1

Example Code

 Live Demo

using namespace std;
main() {
   string str1 = "aabbabababbbaabb";
   string str2 = "abb";
   int pos = 0;
   int index;
   while((index = str1.find(str2, pos)) != string::npos) {
      cout << "Match found at position: " << index << endl;
      pos = index + 1; //new position is from next element of index


Match found at position: 1
Match found at position: 8
Match found at position: 13
Published on 28-Mar-2019 08:28:11