使用string的c_str函数将C++string
转换为字符数组,然后使用strcpy
即可。但是,如何执行相反操作呢?
我有一个字符数组,比如:char arr[ ] = "This is a test";
。需要将其转换为:string str = "This is a test"
。
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;
另一种解决方案可能是这样的,
char arr[] = "mom";
std::cout << "hi " << std::string(arr);
避免使用额外的变量。
在得票最高的答案中,有一个小问题被忽略了。也就是说,字符数组可能包含0。如果我们使用上面提到的单参数构造函数,我们将会丢失一些数据。可能的解决方案是:
cout << string("123\0 123") << endl;
cout << string("123\0 123", 8) << endl;
输出结果为:
123
123 123
std::string
作为二进制数据的容器,并且无法确定数组不包含 '\0',那么这是更好的答案。 - Assil Ksiksi#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
基于原始问题的一点拓展,我通过谷歌搜索“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
const char*
,因此您可以传递一个字符串字面量或字符数组(它会衰减为那个)。 - Mysticialsizeof("hello world")
,它会给你数组的大小(即12),而不是指针的大小(可能是4或8)。 - dreamlaxunsigned char * buffer
声明为传递的参数字符串时,string
构造函数将无法工作,这在字节流处理库中非常普遍。 - CXJstd::string str(buffer, buffer+size);
,但在这种情况下最好坚持使用std::vector<unsigned char>
。 - R. Martinho Fernandesstr
不是转换函数,它是字符串变量的名称。你可以使用任何其他变量名称(例如string foo(arr);
)。转换是由隐式调用的 std::string 构造函数完成的。 - Christopher K.