find_first():
This function is included in the "boost/algorithm/string" library. This library contains some brilliant methods which help in accomplishing string manipulations that are lacking in STL library.
This function is used to find the first occurance of the given pattern in the input string. It starts from the first character of the string and searches for the pattern. Once it finds the pattern, it returns an iterator_range for the rest of the string (pattern inclusive).
header file:
boost/algorithm/string.hpp
boost/range.hpp
syntax:
find_first(input_string,pattern);
parameters:
input_string : an input string
pattern : The patterns to be searched
The return type is iterator_range. i.e., it returns an object fof class iterator_range which can be used to traverse the rest of the string pattern inclusive.
There is another variant of find_first() called ifind_first() is present which searches for the pattern case-insensitively.
SAMPLE CODE:
using namespace std;
using namespace boost::algorithm;
using namespace boost;
int main()
{
//Declaring strings
char s1[] = "Welcome to boost";
char s2[] = "It is very interesting";
char s3[] = "Its very effective";
iterator_range<char*> it1 = find_first(s1,"com");
iterator_range<char*> it2 = find_first(s2,"is");
iterator_range<char*> it3 = find_first(s3,"hi");
//These iterators can also act as a boolean conditions
if(it1)
cout<<it1.begin()<<endl;
if(it2)
cout<<it2.begin()<<endl;
if(it3)
cout<<it3.begin()<<endl;
//using the function directly as a boolean condition
if(find_first("Hello its Safi","Safi"))
cout<<"Safi is present"<<endl;
}
OUTPUT:
EXPLANATION:
As we can observe from the above output, the iterator can be used as boolean condition. i.e., iterator_range is bool convertible. After applying find_first() it returns an iterator to traverse the rest of the string. But for s3, since "hi" is not found, the corresponding it condition fails and no output is obtained.
Comments