(Original) implement a simple string formatting Method

Source: Internet
Author: User

It is very easy to format a string in c #. For example, we can format a string like this:

string str = string.format("test {0}, {1}, {2}, {1}, {0} sample", 1, 2.3, "ok");Console.WriteLine(str);

Output: test 1, 2.3, OK, 2.3, 1 sample

This formatting method is easy to use and supports basic types of parameters, such as int, double, and string. Unfortunately, there are no similar formatting methods in c ++. The boost Library provides a format method, but the c # format method is not simple and flexible. Let's take a look at how boost. format achieves the above formatting:

string str = boost::format("test %1%, %2%, %3%, %4%, %5% sample")%1%2.3%"ok"%2.3%1;cout<<str<<endl;

The problem with boost: format is that many % are required, which is tedious and intuitive to use. C ++ still lacks a format method similar to c #. It is not difficult to implement a similar and simple format. I will implement a simple format with the same basic usage as c, to keep it simple, it does not support complex functions. It only supports conversion of basic types, and the format control of conversion is not supported. It is easy to use. Let's take a look at the specific implementation of format:

#include <tuple>#include <type_traits>#include <string>using namespace std;#include "Variant.hpp"namespace detail{    using Value = Variant<uint8_t, uint16_t, uint32_t, uint64_t, int8_t, int16_t, int32_t, int64_t, float, double, string, char*, const char*>;    char g_buf[2000] = {};    template<size_t k, typename Tuple, typename F>    typename std::enable_if < (k == std::tuple_size<Tuple>::value)>::type GetArgByIndex(size_t, Tuple&, F&, char*&)    {        throw std::invalid_argument("arg index out of range");    }    template<size_t k = 0, typename Tuple, typename F>    typename std::enable_if < (k < std::tuple_size<Tuple>::value)>::type GetArgByIndex(size_t index, Tuple& tp, F& f, char*& p)    {        if (k == index)        {            f(p, std::get<k>(tp));        }        else        {            GetArgByIndex<k + 1>(index, tp, f, p);        }    }    inline int GetIndex(char*& p)    {        char temp[3] = {};        int i = 0;        while (*p != '}'&&*p != '\0')        {            if (i >= 2)                throw std::invalid_argument("index is out of range.");            if (std::isdigit(*p))            {                //push digit                temp[i++] = *p;                char next = *(p + 1);                if (std::isdigit(next))                {                    temp[i++] = next;                    p += 2;                    continue;                }                //validate arg                if (!std::isspace(next) && next != '}')                {                    throw std::invalid_argument("invalid argument.");                }            }            p++;        }        return i == 0 ? -1 : std::atoi(temp);    }    inline void Fun(char*& buf, Value t)    {        t.Visit([&buf](int i)        {            _itoa(i, buf, 10);            buf += i<10 ? 1 : 2;        },            [&buf](double i)        {            auto r = sprintf(buf, "%.15f", i);            buf += r;        },            [&buf](int64_t i)        {            auto r = sprintf(buf, "%"PRId64, i);            buf += r;        },            [&buf](uint64_t i)        {            auto r = sprintf(buf, "%"PRIu64, i);            buf += r;        },            [&buf](const char* p)        {            int len = strlen(p);            memcpy(buf, p, len);            buf += len;        },            [&buf](string& s)        {            memcpy(buf, s.data(), s.size());            buf += s.size();        });    }}template<typename... Args>inline string format(string& str, Args... args){    using namespace detail;    char* buf = g_buf;    auto tp = std::tuple<Args...>(args...);    char* p = (char*) str.c_str();    char* original = p;    int len = str.size() + 1;    int last = 0;    while (*p != '\0')    {        if (*p == '{')        {            //copy content befor {            last = p - original;            memcpy(buf, original, last);            buf += last;            //format args            int index = GetIndex(p);            if (index >= 0)            {                GetArgByIndex<0>(index, tp, Fun, buf);            }            //skip }            original = p + 1;        }        p++;    }    string s = g_buf;    memset(g_buf, 0, buf - g_buf);    return s;}

Let's take a look at the test code:

string str = "it is { 0 }, and {01}, {2}, {01}, {1}";cout<<format(str, 11, 2.1, "tt")<<endl;

Output: it is 11, and 2.1, tt, 2.1 1

The usage is the same as that of c #, which is more convenient than the boost format. This format supports up to 100 parameters (0-99), and the longest formatted string is 2 K. Variant is used in the above implementation. For more information about the implementation of Variant, see the previous blog post: c ++ 11.

 

If you find a better format, please let me know. If not, please click here for recommendations. Thank you. Pai_^

C ++ 11 boost technology exchange group: 296561497. You are welcome to exchange technologies.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.