将 c 样式字符串转换为 c++ 样式字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2242774/
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
converting c style string to c++ style string
提问by assassin
Can anyone please tell me how to convert a C style string (i.e a char* ) to a c++ style string (i.e. std::string) in a C++ program?
谁能告诉我如何在 C++ 程序中将 C 样式字符串(即 char* )转换为 C++ 样式字符串(即 std::string)?
Thanks a lot.
非常感谢。
回答by John Weldon
std::string
can take a char *
as a constructorparameter, and via a number of operators.
std::string
可以将 achar *
作为构造函数参数,并通过多个运算符。
char * mystr = "asdf";
std::string mycppstr(mystr);
or for the language lawyers
或语言律师
const char * mystr = "asdf";
std::string mycppstr(mystr);
回答by zaharpopov
char* cstr = //... some allocated C string
std::string str(cstr);
The contents of cstr
will be copied to str
.
的内容cstr
将被复制到str
.
This can be used in operations too like:
这也可以用于操作:
std::string concat = somestr + std::string(cstr);
Where somestr
is already `std::string``
哪里somestr
已经是 `std::string`
回答by codaddict
You can make use of the string
class constructorwhich takes a char*
as argument.
您可以使用将 a作为参数的string
类构造char*
函数。
char *str = "some c style string";
string obj(str);
回答by quamrana
Another way to do the conversion is to call a function which takes a const std::string&
as a parameter:
进行转换的另一种方法是调用一个将 aconst std::string&
作为参数的函数:
void foo(const std::string& str);
void bar()
{
char* str= ...
foo(str);
}
I think its a lot more tidy to do the conversion at a function call boundary.
我认为在函数调用边界进行转换要整洁得多。