将C风格的字符串转换为C ++ std::string
的最佳方法是什么?在过去,我使用stringstream
s完成了它。有没有更好的办法?
C ++字符串有一个构造函数,可以让你直接从C风格的字符串构造一个std::string
:
const char* myStr = "This is a C string!";
std::string myCppString = myStr;
或者,或者:
std::string myCppString = "This is a C string!";
正如@TrevorHickey在评论中指出的那样,要小心确保正在初始化std::string
的指针不是空指针。如果是,则上述代码会导致未定义的行为。再说一遍,如果你有一个空指针,可能会说你根本就没有字符串。 :-)
检查字符串类的不同构造函数:documentation您可能对以下内容感兴趣:
//string(char* s)
std::string str(cstring);
和:
//string(char* s, size_t n)
std::string str(cstring, len_str);
C++11
:重载一个字符串文字运算符
std::string operator ""_s(const char * str, std::size_t len) {
return std::string(str, len);
}
auto s1 = "abc\0\0def"; // C style string
auto s2 = "abc\0\0def"_s; // C++ style std::string
C++14
:使用std::string_literals
命名空间中的运算符
using namespace std::string_literals;
auto s3 = "abc\0\0def"s; // is a std::string
您可以直接从c字符串初始化std::string
:
std::string s = "i am a c string";
std::string t = std::string("i am one too");
如果你的意思是char*
到std::string
,你可以使用构造函数。
char* a;
std::string s(a);
或者如果string s
已经存在,只需写下:
s=std::string(a);
通常(不声明新存储)您可以使用1-arg构造函数将c-string更改为字符串rvalue:
string xyz = std::string("this is a test") +
std::string(" for the next 60 seconds ") +
std::string("of the emergency broadcast system.");
但是,当构造字符串以通过引用函数(我刚刚遇到的问题)传递它时,这不起作用,例如,
void ProcessString(std::string& username);
ProcessString(std::string("this is a test")); // fails
您需要使引用成为const引用:
void ProcessString(const std::string& username);
ProcessString(std::string("this is a test")); // works.