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?
Thanks a lot.
A C-style string is simply an array of characters that uses a null terminator. A null terminator is a special character ('\0', ascii code 0) used to indicate the end of the string. More generically, A C-style string is called a null-terminated string.
C-strings are simply implemented as a char array which is terminated by a null character (aka 0 ). This last part of the definition is important: all C-strings are char arrays, but not all char arrays are c-strings. C-strings of this form are called “string literals“: const char * str = "This is a string literal.
The c_str() method converts a string to an array of characters with a null character at the end. The function takes in no parameters and returns a pointer to this character array (also called a c-string).
std::string
can take a char *
as a constructor parameter, and via a number of operators.
char * mystr = "asdf";
std::string mycppstr(mystr);
or for the language lawyers
const char * mystr = "asdf";
std::string mycppstr(mystr);
char* cstr = //... some allocated C string
std::string str(cstr);
The contents of cstr
will be copied to str
.
This can be used in operations too like:
std::string concat = somestr + std::string(cstr);
Where somestr
is already `std::string``
You can make use of the string
class constructor which takes a char*
as argument.
char *str = "some c style string";
string obj(str);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With