What is the most effective way to store a char pointer into a string in C++?
The std::string
class has an appropriate constructor that takes a const char *
argument:
const char *p = "hello world";
std::string s = std::string(p);
std::cout << s << std::endl;
That will print
hello world
Basically one of the string constructors is
string (const char* s);
which builds a string using a constant character pointer. This means that you can implicit cast a const char*
to string like
const char* cstr = "Hello, World!";
std::string cppStr = cstr;
Any try to implicitly or explicitly cast a const char*
to std::string
is viable; for instance
cppStr = cppStr + cstr;
Or you could just call the constructor and pass the parameters
std::string cppstr2 {cstr};
If you have a constexpr
it would be a string literal and most compilers convert string literal into std::string
at compile time making its time complexity constant. However converting a constant pointer or a conventional c_string to a std::string
takes linear time.
More info on std::string
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.