[英]Converting a C-style string to a C++ std::string
將C風格的字符串轉換為C ++ std::string
的最佳方法是什么? 在過去,我使用stringstream
s完成了它。 有沒有更好的辦法?
C ++字符串有一個構造函數,可以直接從C風格的字符串構造一個std::string
string:
const char* myStr = "This is a C string!";
std::string myCppString = myStr;
或者,或者:
std::string myCppString = "This is a C string!";
正如@TrevorHickey在注釋中注意到的那樣,要小心確保初始化std::string
指針不是空指針。 如果是,則上述代碼會導致未定義的行為。 再說一遍,如果你有一個空指針,可能會說你根本就沒有字符串。 :-)
檢查字符串類的不同構造函數: 文檔您可能感興趣:
//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
如果你的意思是char*
到std::string
,你可以使用構造函數。
char* a;
std::string s(a);
或者如果string s
已經存在,只需寫下:
s=std::string(a);
您可以直接從c-string初始化std::string
string:
std::string s = "i am a c string";
std::string t = std::string("i am one too");
通常(不聲明新存儲)您可以使用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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.