我声明了一个 char * 数组 char *excluded_string[50] = { 0 };
之后,ex_str 数组的每个元素都得到了一个单词。现在我想将它转换为字符串,以便我可以将所有单词用空格分隔开。
要将它转换为单个字符串:
char *excluded_string[50] = { 0 };
std::ostringstream buffer;
for(int i = 0; i < 50; ++i)
buffer << excluded_string[i] << " ";
std::string result = buffer.str();
编辑:几点注意事项:
如果可能,请勿直接连接字符串:这将创建和销毁大量对象,并执行许多不必要的分配。
如果您的代码具有严格的效率要求,请考虑预先分配/保留结果,以确保单个分配而不是重复分配。
如果要连接字符串,请考虑使用 operator += 而不是 + 和 =。
编辑2:(回答评论)
如果使用 + 和 = 而不是 += 呢?
下面是连接字符串的两种方案 (s += s1 + s2 vs s += s1; s += s2) 的解决方案:
代码:
std::string ss;
for (int i=0; i<50; i++)
ss += std::string(excluded_string[i]) + " ";
等价的代码(根据构造的对象和分配来衡量):
std::string ss;
for (int i=0; i<50; i++)
{
std::string temp1(excluded_string[i]);
std::string temp2 = temp1 + " ";
ss += temp2;
}
- 每次迭代都会创建temp1;
- 为连接运算符创建temp2
- 第二个临时变量被附加到ss。
这两个临时变量都会创建数据的副本(分配缓冲区,复制数据,释放缓冲区)。
代码:
std::string ss;
for (int i=0; i<50; i++)
{
ss += excluded_string[i];
ss += " ";
}
预先分配/保留结果,以确保单个分配。
std::size_t total_length = 0
for(int i = 0
total_length += std::strlen(excluded_strings[i])
std::string ss
ss.reserve(total_length + 51)
for (int i=0
{
ss += excluded_string[i]
ss += " "
}
在这种情况下,operator+= 不会在内部分配空间,只是在开头进行一次操作。这仍然有点慢,因为您需要两次迭代字符串(0->49),并且需要两次迭代每个字符串(一次计算长度,一次将其复制到ss)。
如果您的 excluded_string 改为 std::vector,则会更高效,因为计算字符串长度时不需要迭代每个字符串,只需要迭代向量本身。