如何将char *数组转换为std :: string

用户123

我声明了一个char *数组 char *excluded_string[50] = { 0 };

之后,excluded_string数组的每个元素得到一个单词。现在,我想将其转换为字符串,以便可以用空格分隔所有单词。

std::string ss(excluded_string); 给出错误:

`server.cpp:171:32:错误:没有匹配的函数来调用'std :: basic_string :: basic_string(char * [50])'和大量棘手的解释!

乌他匹斯汀

我声明了char * array char * excluded_string [50] = {0};

之后,ex_str数组的每个元素都得到一个单词。现在,我想将其转换为字符串,以便可以用空格分隔所有单词。

要将其转换为单个字符串:

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 :(回答评论)

如果用+和=而不是+ =怎么办?

这是连接字符串的两种选择的解决方案(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)。

如果您的exclude_string是std :: vector,则效率会更高,因为计算字符串的长度不会对每个字符串(仅是向量)进行迭代。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章