In this article we will discuss how to find a Case Insensitive Sub String in a given string in C++ using,

  • STL
  • Boost Library

std::string provides a method std::string::find to search for the sub string inside a given string, but this function is case sensitive i.e.

In above code, value of pos will be std::string::npos i.e.

Because, std::string::find is case sensitive and can not find ‘SAMPLE’ in the given string.  Now let’s implement a case sensitive version of std::string::find

Finding A Case Insensitive Sub String in C++ using STL

Logic:

Create a new find function that will convert both the given string and sub string to lower case and then use the std::string::find to search sub string in the string i.e.

Let’s see how to use this function,

Unlike std::string::find, here we are able to find “SAMPLE” in “Hi this is a sample string”

Complete code example is as follows,

Output

Finding A Case Insensitive Sub String using Boost::icontains

With boost::icontains we can check if a sub string exists in a given string i.e.

But we can not find out the position of substring with it 🙁

Complete code example is as follows,

Output