Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting c style string to c++ style string

Tags:

c++

c-strings

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.

like image 623
assassin Avatar asked Feb 11 '10 06:02

assassin


People also ask

What is the C-style character string?

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.

What is the difference between CString and 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.

What does c_str () do in C++?

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).


3 Answers

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);
like image 84
John Weldon Avatar answered Oct 16 '22 09:10

John Weldon


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``

like image 10
zaharpopov Avatar answered Oct 16 '22 11:10

zaharpopov


You can make use of the string class constructor which takes a char* as argument.

char *str = "some c style string";
string obj(str);
like image 3
codaddict Avatar answered Oct 16 '22 11:10

codaddict