In this article we will discuss how to find all occurrences / Positions of a sub string in a given string in both case sensitive & case insensitive manner.

Find All Case Sensitive Occurrences of a Sub String in a given String


Use std::string::find to search the first occurrence and then go on searching using same logic from that position onward, till you reach the end.

Complete example is as follows,


As it’s internally using std::string::find to the sub string therefore it is case sensitive and able to find 3 occurrences only.

Find All Case Sensitive occurrence of a Sub String in a given String

We will use the same logic as above i.e. keep on search the occurrences of sub string till reaches the end.
But to find an occurrence of sub string, we will use customized case insensitive version of std::string::find .

Checkout the complete code as follows,



Because we are using case insensitive version of std::string::find, therefore we will get 4 reparations of sub string.

Generic Find All Implementation

We don’t need to maintain 2 separate functions to find all occurrences, we can create a generic find_all function, that will accept String Finder function as callback and use it to find repeated occurrences of sub strings i.e.

Let’s use this above function to find case insensitive substrings by passing findCaseInsensitive as callback

Let’s use this above function to find case sensitive substrings by passing std::string::find as callback i.e.

Complete example is as follows,




Click Here to Subscribe for more Articles / Tutorials like this.