将 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:40:55  来源:igfitidea点击:

converting c style string to c++ style string

c++c-strings

提问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::stringcan 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 cstrwill be copied to str.

的内容cstr将被复制到str.

This can be used in operations too like:

这也可以用于操作:

std::string concat = somestr + std::string(cstr);

Where somestris already `std::string``

哪里somestr已经是 `std::string`

回答by codaddict

You can make use of the stringclass 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.

我认为在函数调用边界进行转换要整洁得多。