Search code examples
c++stringc++17tostring

c++17 fast way for trans int to string with prefix '0'


I want to trans an int into string. I known under c++17, a better way is using std::to_string.

But now I want to fill the prefix with several '0'. For example, int i = 1, std::to_string(i) is '1', but I want the result is '00001'(total lenght is 5).

I know using sprintf or stringstream may achieve that. But which have a better performance or some other way?


Solution

  • If you know something about your domain and don't need to check for errors, nothing gets faster than rolling your own. For example if you know that your int is always in the range [0, 99'999], you could just:

    std::string
    convert(unsigned i)
    {
        std::string r(5, '0');
        char* s = r.data() + 4;
        do
        {
            *s-- = static_cast<char>(i%10 + '0');
            i /= 10;
        } while (i > 0);
        return r;
    }
    

    General purpose libraries don't have the luxury of making such assumptions.