【发布时间】:2012-02-16 02:54:12
【问题描述】:
使用字符串的c_str 函数然后执行strcpy 将C++ string 转换为char 数组非常简单。但是,如何做到相反呢?
我有一个 char 数组,例如:char arr[ ] = "This is a test"; 要转换回:
string str = "This is a test.
【问题讨论】:
使用字符串的c_str 函数然后执行strcpy 将C++ string 转换为char 数组非常简单。但是,如何做到相反呢?
我有一个 char 数组,例如:char arr[ ] = "This is a test"; 要转换回:
string str = "This is a test.
【问题讨论】:
#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;
输出是:
123
123 123
【讨论】:
std::string 作为二进制数据的容器并且不能确定该数组不包含“\0”,这是一个更好的答案。
另一种解决方案可能如下所示,
char arr[] = "mom";
std::cout << "hi " << std::string(arr);
避免使用额外的变量。
【讨论】:
std::string 构造函数提供一个长度,例如 this answer。
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;
【讨论】:
const char*,因此您可以将字符串文字或字符数组传递给它(衰减到那个)。
"hello world" 形式的字符串是数组。如果您使用sizeof("hello world"),它将为您提供数组的大小(即 12),而不是指针的大小(可能是 4 或 8)。
string 构造函数不适用于例如声明为 unsigned char * buffer 的传递参数字符串,这在字节流处理库中很常见。
std::string str(buffer, buffer+size);,但在这种情况下最好坚持使用std::vector<unsigned char>。
str 在这里 不是 转换函数。它是字符串变量的名称。您可以使用任何其他变量名称(例如 string foo(arr);)。转换由隐式调用的 std::string 的构造函数完成。