c++ 如何有效地格式化带有集合的std::string?

问题描述 投票:0回答:1

我有一个程序,它有一个字符串(需要格式化),并从一个外部资源中获取一个元素集合。字符串必须使用集合中的元素进行格式化,这些元素是std::string。我不能手动格式化字符串,比如。

// Just examples
sprintf(test, "%s this is my %s. This is a number: %d.", var[0], var[1], etc..);        // i can't do this
fmt::printf("%s this is my %s. This is a number: %d.", var[0], var[1], etc..);          // i can't do this (i also have fmt library)

因为集合中元素的数量是可变的。我想做的是尽可能有效的格式化字符串。

这是我的代码。

std::string test = "%s this is my %s. This is a number: %d.";
std::vector<std::string> vec;

vec.push_back("Hello");
vec.push_back("string");
vec.push_back("5");


// String Formatting
std::size_t found;
for (auto i : vec)
{
    found = test.find("%");
    if (found != std::string::npos)
    {
        test.erase(found, 2);
        test.insert(found, i);
    }
}

std::cout << test;

注1:我使用了一个std::vector来管理集合中的元素,但我可以使用任何其他结构。

这就是为什么我没有把定义放在代码中的原因。此外,我写的代码在我有一个带百分比的字符串的情况下是不能用的,比如。

std::string test = "%s this is a percentage: %d%%. This is a number: %d.";
// Output = "Hello this is a percentage: string5. This is a number: %d."

总之,什么是最有效的格式化多元素字符串的方法?即使不使用向量,但使用其他结构。或者使用fmt或者boost?也许boost会降低效率)我的开发环境是Visual Studio 2019。

c++ string-formatting stdvector stdstring fmt
1个回答
0
投票

你可以使用{fmt}最近添加的 dynamic_format_arg_store (https:/github.comfmtlibfmtreleasestag6.2.0。):

#include <fmt/format.h>

int main() {
  fmt::dynamic_format_arg_store<fmt::format_context> args;
  args.push_back("Hello");
  args.push_back("string");
  args.push_back("5");
  fmt::vprint("{} this is my {}. This is a number: {}.", args);
}

这将打印(https:/godbolt.orgzjUbbUi):

Hello this is my string. This is a number: 5.

请注意,{fmt}使用 {} 而不是 % 用于替换领域。

© www.soinside.com 2019 - 2024. All rights reserved.