std::string的format实现方式

template< typename... Args >
std::string string_sprintf(const char* format, Args... args) {
    int length = std::snprintf(nullptr, 0, format, args...);
    if (length <= 0) {
        return "";
    }

    char* buf = new char[length + 1];
    std::snprintf(buf, length + 1, format, args...);

    std::string str(buf);
    delete[] buf;
    return std::move(str);
}

string s = "拉拉黑%saaaa你好"; string x = string_sprintf(s.c_str(), "123");

输出:
拉拉黑123aaaa你好

完美

猜你喜欢

转载自www.cnblogs.com/yylingyao/p/11771579.html
今日推荐