In this article we will discuss both case sensitive and insensitive implementations to check if a string starts with an another given string.

In c++, std::string class does not provides any startsWith() function to check if a string starts with an another given string. Let’s see how to do that using std::string::find and Boost Library.

std::string startWith() Implementation using std::string::find

std::string class provides a member function find(), that accepts a string and search for first occurrence of that in the associated string object. If string matches then it returns the position of matched string else return std::string::npos.

For startsWith() implementation let’s use std:string::find to find the first occurrence of given string. If returned position is 0, then it will make sure that our main string starts with the given string.

Case Sensitive Implementation of startsWith() function using std::find

Case Insensitive Implementation of startsWith() function using std::find

For case insensitive implementation of startsWith(), first convert both to lower case and then use std::string::find to check the position of given string.

Check complete example as follows,

Output:

std::string startWith() using Boost Library

Boost’s algorithm library provides implementation of both case sensitive and insensitive implementation of startsWith() function for string i.e.

case Sensitive Version :

case Insensitive Version :

Header File required : <boost/algorithm/string.hpp>

Checkout complete example as follows,

 

Output:

 

 

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