C++17 split constexpr string on comma and have the number of elements at compile time?
I would like to convert the char array to string, then split on "," and have the number of elements available at compile time.
If for "string" do you mean "std::string
", it isn't constexpr
so it's incompatible with a compile time computation.
If for "string" you accept the C-style string, a char const *
, and if you're interested in separators of a single char
, you can try something as follows
#include <iostream>
constexpr static char arrayStr[] = "a,b,c";
constexpr std::size_t SPLIT (char const * str, char sep)
{
std::size_t ret { 1u };
while ( *str )
if ( sep == *str++ )
++ ret;
return ret;
}
int main ()
{
constexpr auto numFields = SPLIT(arrayStr, ',');
std::cout << numFields << std::endl; // print 3
}