This post will discuss how to check if a string starts with a certain string in C++.

1. Using string::rfind

The string::rfind function searches the string for the last occurrence of the specified string, starting at or before the specified position. To check whether a string starts with the specified string, pass position 0.

Download  Run Code

Output:

String starts with the given prefix

2. Using string::compare

The string::compare function compares the value of a string with the specified sequence of characters. A zero status code indicates the strings are equal. It can be used as follows to match against a prefix:

Download  Run Code

Output:

String starts with the given prefix

3. Using Boost

If you already use boost library in your project, consider using the boost::algorithm::starts_with function from header <boost/algorithm/string/predicate.hpp>. It returns true if the input starts with the prefix.

Download Code

Output:

String starts with the given prefix

4. Using string::substr

The string::substr function returns a substring of a string between specified positions. It can be used as follows to match a string against a prefix:

Download  Run Code

Output:

String starts with the given prefix

5. Using string::starts_with

Starting with C++20, we can use the string::starts_with function, which returns true if the string starts with the specified prefix. This is demonstrated below:

Download Code

Output:

String starts with the given prefix

6. Using std::mismatch

Finally, the STL library offers the std::mismatch algorithm, which compares the elements in two specified ranges and returns a pair specifying the first position where they differ. It can be used as follows, to check if the string starts with a certain string.

Download  Run Code

Output:

String starts with the given prefix

That’s all about checking if a string starts with a certain string in C++.