Up to (and including) C++17 if you wanted to check the start or the end in a string you have to use custom solutions, boost or other third-party libraries. Fortunately, this changes with C++20.
See the article where I’ll show you the new functionalities and discuss a couple of examples.
_This article was originally published at _bfilipek.com.
Here’s the main proposal that was added into C++20:
C++
std::string/std::string_view .starts_with() and .ends_with() P0457
In the new C++ Standard, we’ll get the following member functions for std::string
and std::string_view
:
C++
constexpr bool starts_with(string_view sv) const noexcept;
constexpr bool starts_with(CharT c ) const noexcept;
constexpr bool starts_with(const CharT* s ) const;
And also for suffix checking:
C++
constexpr bool ends_with(string_view sv )const noexcept;
constexpr bool ends_with(CharT c ) const noexcept;
constexpr bool ends_with(const CharT* s ) const;
As you can see, they have three overloads: for a string_view
, a single character and a string literal.
Simple example:
C++
const std::string url { "https://isocpp.org" };
// string literals
if (url.starts_with("https") && url.ends_with(".org"))
std::cout << "you're using the correct site!\n";
// a single char:
if (url.starts_with('h') && url.ends_with('g'))
std::cout << "letters matched!\n";
You can play with this basic example @Wandbox
#tutorial #iot #c++ #visual c++ #vc++ #c++20 #string view prefixes #string view suffixes