如何将字符数组转换为字符串?

295

使用string的c_str函数将C++string转换为字符数组,然后使用strcpy即可。但是,如何执行相反操作呢?

我有一个字符数组,比如:char arr[ ] = "This is a test";。需要将其转换为:string str = "This is a test"

5个回答

418

string类有一个构造函数,可以接受以NULL结尾的C字符串:

char arr[ ] = "This is a test";

string str(arr);


//  You can also assign directly to a string.
str = "This is another string";

// or
str = arr;

2
无论哪种方式都可以正常工作。重载的赋值运算符接受一个 const char*,因此您可以传递一个字符串字面量或字符数组(它会衰减为那个)。 - Mysticial
3
严格来说,形如“hello world”的字符串数组。如果你使用sizeof("hello world"),它会给你数组的大小(即12),而不是指针的大小(可能是4或8)。 - dreamlax
17
请注意,这仅适用于常量以NULL结尾的C字符串。例如,使用unsigned char * buffer声明为传递的参数字符串时,string构造函数将无法工作,这在字节流处理库中非常普遍。 - CXJ
6
没必要让任何东西保持不变。如果您有任何char类型的字节缓冲区,可以使用另一个构造函数:std::string str(buffer, buffer+size);,但在这种情况下最好坚持使用std::vector<unsigned char> - R. Martinho Fernandes
4
虽然这可能很明显:在这里 str 不是转换函数,它是字符串变量的名称。你可以使用任何其他变量名称(例如 string foo(arr);)。转换是由隐式调用的 std::string 构造函数完成的。 - Christopher K.
显示剩余8条评论

62

另一种解决方案可能是这样的,

char arr[] = "mom";
std::cout << "hi " << std::string(arr);

避免使用额外的变量。


你能在回答中指出这与Misticial的被接受答案有何不同吗? - Maarten Bodewes
1
@owlstead 请查看编辑。我只是提供了我的答案,因为这就是我第一次查找答案时希望看到的内容。如果有像我一样愚蠢的人查看此页面,但无法从第一个答案中得出结论,我希望我的答案能对他们有所帮助。 - stackPusher
这通常不适用于字符数组,只有当它们以0结尾时才适用。如果您无法确保您的字符数组以0结尾,请像此答案中那样为std::string构造函数提供长度。 - stackprotector

58

在得票最高的答案中,有一个小问题被忽略了。也就是说,字符数组可能包含0。如果我们使用上面提到的单参数构造函数,我们将会丢失一些数据。可能的解决方案是:

cout << string("123\0 123") << endl;
cout << string("123\0 123", 8) << endl;

输出结果为:

123
123 123


4
如果您使用 std::string 作为二进制数据的容器,并且无法确定数组不包含 '\0',那么这是更好的答案。 - Assil Ksiksi
或者如果字符串数组不包含'\0' - Brian Yeh

12
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string>

using namespace std;

int main ()
{
  char *tmp = (char *)malloc(128);
  int n=sprintf(tmp, "Hello from Chile.");

  string tmp_str = tmp;


  cout << *tmp << " : is a char array beginning with " <<n <<" chars long\n" << endl;
  cout << tmp_str << " : is a string with " <<n <<" chars long\n" << endl;

 free(tmp); 
 return 0;
}

OUT:

H : is a char array beginning with 17 chars long

Hello from Chile. :is a string with 17 chars long

free(tmp)在哪里?字符串是否负责释放它? - huseyin tugrul buyukisik
2
好问题。我认为应该有free,因为我正在使用malloc。 - Cristian

2

基于原始问题的一点拓展,我通过谷歌搜索“c++将std::array中的char转换为字符串”,结果跳转到了这里,然而现有答案都没有涉及到std::array<char, ..>:

#include <string>
#include <iostream>
#include <array>
 
int main()
{
  // initialize a char array with "hello\0";
  std::array<char, 6> bar{"hello"};
  // create a string from it using the .data() ptr,
  // this uses the `const char*` ctor of the string
  std::string myString(bar.data());
  // output
  std::cout << myString << std::endl;

  return 0;
}

输出

hello

Demonstration


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接