Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a constexpr version of strstr()?

Tags:

c++

constexpr

As I understand it, the traditional character array functions, like strlen, strstr etc are all defined by the C-standard, and since constexpr is C++11, they're not declared with it.

However, the std::char_traits in C++17 define some equivalent functions like find (which is essentially a constexpr C++ version of strchr, or copy which appears to provide something similar to strcpy.

But there's no variant of find that finds a substring, only a single char. So is there some C++ constexpr equivalent of strstr part of the standard anywhere?

like image 678
Dan Forever Avatar asked Dec 05 '19 10:12

Dan Forever


1 Answers

As mentioned in the comments, you can use std::string_view:

#include <string_view>

constexpr std::string_view sv1 = "Hello World!";

static_assert(sv1.find("Hello") == 0);
static_assert(sv1.find("World") == 6);
static_assert(sv1.find("olleh") == std::string_view::npos);

std::string_view constructors are all constexpr, so you can construct one from a string-literal, and the .find() methods are also constexpr.

like image 110
Holt Avatar answered Nov 19 '22 12:11

Holt