如何将字符数组转换为字符串?
问题描述:
使用字符串的c_str
函数然后执行strcpy
将C++ string
转换为char 数组非常简单.但是,如何做相反的事情?
Converting a C++ string
to a char array is pretty straightorward using the c_str
function of string and then doing strcpy
. However, how to do the opposite?
我有一个字符数组,如:char arr[] = "This is a test";
要转换回:string str = "这是一个测试
.
I have a char array like: char arr[ ] = "This is a test";
to be converted back to:
string str = "This is a test
.
答
string
类有一个构造函数,它接受一个以 NULL 结尾的 C 字符串:
The string
class has a constructor that takes a NULL-terminated 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;