将字符串向量中的字符串放入主字符串中

placing strings from a string vector into main string

本文关键字:字符串 向量      更新时间:2023-10-16

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

#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 矢量内的字符串替换事件字符串中的 %s 标志。 但是我得到了Segmentation fault (core dumped)错误。

你能指出我的错误吗?

编辑

矢量的长度是可变的。我有一个字符串模板,其中包含可变数量的%s标志,我正在尝试编写一个函数,我们可以在其中传递一个向量并将这些标志替换为 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

我认为aCraig5075有正确的方法。 以下是利用向量的类似内容:

int main()
{
std::string event {"this is %s, %s and %s"};
std::string flag = "%s";
std::vector<std::string> strs = {"sam", "joey", "chandler", "fred"};
std::vector<std::string>::iterator it = strs.begin();
std::size_t found = event.find(flag);
while (it != strs.end() && found != std::string::npos) {  //terminates at shortest
event.replace(found, flag.length(), *it);
found = event.find(flag);
++it;
}
std::cout << event << std::endl;
}

如果字符串中的标志数量与向量中的字符串数量不匹配,这将很好地发挥作用,如果其中任何一个耗尽,则会停止循环。

您尝试对sprintf进行三次单独的调用,但在每次调用中,您都会传递三次%s转换,因此第一次尝试打印出三个字符串,即使您只传递了一个字符串。如果它完成了第一次迭代的执行,在第二次迭代中,您将再次执行相同的操作:传递一个字符串,但告诉它期望三个字符串。第三次也一样。

不过,我完全不清楚你为什么要这样做。您可以使用以下顺序的代码生成您似乎想要的输出:

std::vector<string> strs = {"sam", "joey", "chandler"};
std::cout << "This is: " << strs[0] << ", " << strs[1] << " and " << strs[2];

你可以看看 sprintf 的用法,如果你想继续使用你的代码格式,我的方法是:

#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];
sprintf(buffer, event, strs[0].c_str(),strs[1].c_str(),strs[2].c_str());
std::cout << buffer<<endl;
return 0;
}