Saturday, October 4, 2014

c++ string to char array

C++ standard template library (STL) string A.K.A std::string was a novel concept back in the day when it was first introduced to the programming community with C++ programming language. Now we see every programming language be it Java or C# or Ruby contains an excellent implementation of string. Similarities between the modern string libraries can be traced back to yesteryear's string.h header file.

It is important to note that the std::string classes were actually a wrapper around C style null terminated character pointer string.

c-plus-plus-string-char-array-code

Even the apparently sophisticated(and complicated) BSTR of COM era are just a sequence of characters with some meta data(i.e. length of string).

c++ string to char* code

Since we know every std::string actually contains a char * (read character pointer) buffer in the background, there must be some way to convert C++ string to C style char array. The character arrays are also called zero terminated strings.







The good news is that there is a function in std::string class which lets us retrieve the const char * which is in the background of the string instance. The method is called

c_str

An exact example in code about how to use std::string.c_str() function is given below.

Code C++ string to char * or char array

using namespace std;

#include<string>
#include<iostream>

int main(int argc, char* argv[])
{
 std::string strILoveYou = "i<3U";// new object of std::string

 const char * szMe2 = strILoveYou.c_str();// new object of c style null terminated character pointer

 cout << strILoveYou << endl; 
 cout << szMe2  << endl;

 return 0;
}// code highligting with http://tohtml.com/cpp/


You must have noticed that the const char * retrieved this way is read only. If you want to extract a changeable string out of std::string we'll need to add a couple of lines to the code. We will use the strcpy C function, some might argue that this is not true C++ but I say everything from C is in the genesis of C++ so there's nothing untrue to spirit of C++ if we use functions from the C programming language which is the mother of all languages. The new code will look like

using namespace std;

#include<string>
#include<iostream>

int main(int argc, char* argv[])
{
 std::string strILoveYou = "i<3U";

 const char * szMe2 = strILoveYou.c_str();

 char * notConstantCharPtr = new char[strILoveYou.length()]; 
 strcpy(notConstantCharPtr, strILoveYou.c_str());

 cout << strILoveYou  << endl; 
 cout << szMe2   << endl;
 cout << notConstantCharPtr << endl;

 return 0;
}// highlight with tohtml.com/cpp

HAPPY CODING FELLAS!!!
I hope you found this small programming tutorial to be useful. Please do check my online courses which are listed on the top right of this page.

1 comment:

Feel free to talk back...