C++ 如何将字符数组转换为字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8960087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a char array to a string?
提问by kingsmasher1
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?
string
使用c_str
string 函数将 C++转换为 char 数组非常简单,然后执行strcpy
. 然而,如何做相反的事情呢?
I have a char array like: char arr[ ] = "This is a test";
to be converted back to:
string str = "This is a test
.
我有一个字符数组,如:char arr[ ] = "This is a test";
要转换回:
string str = "This is a test
。
回答by Mysticial
The string
class has a constructor that takes a NULL-terminated C-string:
本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;
回答by stackPusher
Another solution might look like this,
另一种解决方案可能如下所示,
char arr[] = "mom";
std::cout << "hi " << std::string(arr);
which avoids using an extra variable.
这避免了使用额外的变量。
回答by Yola
There is a small problem missed in top-voted answers. Namely, character array may contain 0. If we will use constructor with single parameter as pointed above we will lose some data. The possible solution is:
最高投票的答案中遗漏了一个小问题。也就是说,字符数组可能包含 0。如果我们使用上面指出的带有单个参数的构造函数,我们将丢失一些数据。可能的解决方案是:
cout << string("123#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;
}
123") << endl;
cout << string("123H : is a char array beginning with 17 chars long
Hello from Chile. :is a string with 17 chars long
123", 8) << endl;
Output is:
输出是:
123
123 123
123
123 123
回答by Cristian
OUT:
出去:
##代码##