Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create alphabet string at compile time

Tags:

c++

I want to create a collection of ASCII characters, at compile time, containing the alphabet.
Something like this works fine:

consteval std::string_view get_alphabet()
{
    std::string_view sv = "ABCDE ... XYZ";

    return sv;
}

However, to avoid typos, I would like to use iota to create the collection.
Is there a way I can populate some character collection, at compile time, and wrap it in a std::string_view ?

This is the idea, but it only works at runtime.

std::string_view get_alphabet()
{
    static std::string s(26, 0);

    std::iota(s.begin(), s.end(), 'A');

    return s;
}
like image 768
Tootsie Avatar asked Oct 19 '25 02:10

Tootsie


1 Answers

You can define a const array holding the alphabet like this:

#include <array>

constexpr auto get_alphabet()
{
    return []<std::size_t...Is>(std::index_sequence<Is...>){
        return std::array<char,26>{{ 'A'+ Is... }};
    }(std::make_index_sequence<26>());
}

static_assert (get_alphabet() == std::array<char,26> { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' });

int main()
{
}

DEMO

Note that I made no typo while writing the static_assert ;)

update

As Konrad Rudolph pinpointed, one can also go directly for a std::string_view (requires c++23 though while the snippet above requires c++20 only)

#include <array>
#include <string_view>

constexpr auto get_alphabet ()
{
    static constexpr std::array<char,26> arr =  []<std::size_t...Is>(std::index_sequence<Is...>){
        return std::array<char,26>{{ 'A'+ Is... }};
    } (std::make_index_sequence<26>());
    
    return std::string_view (arr.begin(),arr.end()); 
}

static_assert (get_alphabet().size() == 26);
static_assert (get_alphabet() == std::string_view { "ABCDEFGHIJKLMNOPQRSTUVWXYZ" });

int main() {}
like image 191
abcdefg Avatar answered Oct 21 '25 16:10

abcdefg