Search code examples
c++stlfunctionprefixes

Function in c++ for finding if a word is prefix


Let say i have some words AB, AAB, AA.

AB is not a prefix to AAB but AA is a prefix to AAB because if i just add B at the end of AA it will become AAB, which is not possible with AB.

So, is there any function in c++ (STL) so that i can determine of two words if one is prefix to the another ?

Thanks.


Solution

  • template<class C, class T, class A>
    bool starts_with(std::basic_string<C,T,A> const& haystack,
                     std::basic_string<C,T,A> const& needle)
    {
      return needle.length() <= haystack.length() &&
        std::equal(needle.begin(), needle.end(), haystack.begin());
    }
    

    Note that the length check is not premature optimization, it is required to meet std::equal's precondition.