gpt4 book ai didi

c++ - 将字符串 vector 中的字符串放入主字符串中

转载 作者:行者123 更新时间:2023-12-02 01:53:40 27 4
gpt4 key购买 nike

我想将字符串从字符串 vector 放置到字符串中。这是我尝试过的代码:

#include <iostream>
#include <cstdio>
#include <vector>
#include <string>

using namespace std;

int main()
{
const char* event = "this is %s, %s and %s";
std::vector<string> strs = {"sam", "joey", "chandler"};
char buffer[200];

std::vector<string>::iterator it;

for(it = strs.begin(); it < strs.end(); it++)
{
sprintf(buffer, event, it->c_str());
}

std::cout << buffer;
return 0;
}

我期望的结果是它将用 strs vector 中的字符串替换事件字符串中的 %s 标志。但是我遇到了段错误(核心转储)错误。

请您指出我的错误。

编辑

vector 的长度是可变的。我有一个带有可变数量 %s 标志的字符串模板,我正在尝试编写一个函数,在其中我们可以传递 vector 并用 vector 中的字符串替换这些标志。

这些字符串的示例是:“你好%s,遇见%s”“欢迎%s”“今天是 %s,我们希望 %s 与您合作”

最佳答案

你的错误是 printf 显然不适合你想做的事情。我建议简单的子字符串 "%s" 搜索和替换。这很简单,而且肯定更安全。

std::string formatter(const char* event, const std::vector<string> &strs) {
std::string buffer(event);

size_t off = 0;
for (auto placeholder : strs) {
size_t i = buffer.find("%s", off);
if (i == std::string::npos)
break;

buffer.erase(i, 2);
buffer.insert(i, placeholder);
off = i;
}

return buffer;
}

int main() {
std::cout << formatter("this is %s, %s and %s", { { "sam", "joey", "chandler" } }) << "\n";
std::cout << formatter("welcome %s", { { "sam", "joey", "chandler" } }) << "\n";
std::cout << formatter("today is %s, and we want %s to work with you", { { "sam", "joey", "chandler" } }) << "\n";
}

产品

this is sam, joey and chandler
welcome sam
today is sam, and we want joey to work with you

关于c++ - 将字符串 vector 中的字符串放入主字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59781742/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com