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

将c++ string转换为char数组非常简单,使用string的c_str函数,然后执行strcpy。然而,如何做到相反呢?

我有一个像:char arr[ ] = "This is a test";这样的字符数组要转换回: string str = "This is a test . < / p >
964153 次浏览

string类有一个构造函数,它接受一个以null结束的C-string:

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;

另一个解可能是这样的,

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

这避免了使用额外的变量。

#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;
}

:

H : is a char array beginning with 17 chars long


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

投票最多的答案中漏掉了一个小问题。即字符数组可以包含0。如果我们将使用单参数构造函数如上所述,我们将丢失一些数据。可能的解决方案是:

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

输出是:

< p > 123 < br > 123 123 < / p >

A bit <O/T>基于OP,但我谷歌&;c++ convert std::array char to string&;它把我带到这里,但没有一个现有的答案处理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

示范