我声明了一个 char * 数组 char *excluded_string[50] = { 0 };
稍后 excluded_string
数组的每个元素都得到一个单词。现在我想将它转换成字符串,这样我就可以用空格分隔所有单词。
std::string ss(excluded_string);
给出错误:
`server.cpp:171:32: error: no matching function for call to ‘std::basic_string::basic_string(char* [50])’ and large tricky explaination!
最佳答案
I declared char * array char *excluded_string[50] = { 0 };
Later each element of ex_str array gets one word. Now I want to convert it into string so that I can have all words seperated by space.
将其转换为单个字符串:
char *excluded_string[50] = { 0 };
// excluded_string filled in the meantime
std::ostringstream buffer; // add #include <sstream> at the top of
// the file for this
for(int i = 0; i < 50; ++i)
buffer << excluded_string[i] << " ";
std::string result = buffer.str();
编辑:一些注意事项:
如果可能,不要直接连接字符串:这会创建和销毁大量对象并执行大量不必要的分配。
如果您的代码有严格的效率要求,请考虑预先分配/保留结果以确保单次分配而不是重复分配。
如果您连接字符串,请考虑使用运算符 += 而不是 + 和 =。
编辑 2:(回答评论)
What if + and = instead of +=?
这里是连接字符串的两个替代方案的解决方案(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++)
{
// ss += std::string(excluded_string[i]) + " ";
std::string temp1(excluded_string[i]); // "std::string(excluded_string[i])"
std::string temp2 = temp1 + " "; // call std::string operator+(std::string, char*)
ss += temp2; // call std::string::operator +=(std::string)
}
- temp1 每次迭代创建一次;
- temp2 是为串联运算符创建的
- 第二个临时文件附加到 ss。
两个临时对象都创建数据拷贝(分配缓冲区、复制数据、释放缓冲区)。
- 使用 += 两次:
代码:
std::string ss;
for (int i=0; i<50; i++)
{
ss += excluded_string[i]; // call std::string::operator +=(char*)
ss += " "; // same as above
}
std::string::operator += 被调用两次;它分配空间(如有必要),将字符串的当前内容复制到新分配的空间,然后在分配的缓冲区末尾复制新数据。
单个预分配空间:
预先分配/保留结果以确保单个分配
std::size_t total_length = 0;
for(int i = 0; i < 50; ++i)
total_length += std::strlen(excluded_strings[i]); // assumes argument is not null
std::string ss;
ss.reserve(total_length + 51); // reserve space for the strings and spaces between
for (int i=0; i<50; i++)
{
ss += excluded_string[i]; // calls std::string::operator +=
ss += " "; // same as above
}
在这种情况下,operator+= 不会在内部分配空间,只是在开始时(单个操作)。这仍然有点慢,因为您遍历字符串两次 (0->49) 并遍历每个字符串两次(一次计算长度,一次将其复制到 ss)。
如果您的 excluded_string 是一个 std::vector,它会更有效,因为计算字符串长度不会迭代每个字符串,只会迭代 vector )。
关于c++ - 如何将 char* 数组转换为 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18400475/