Saturday, October 4, 2014

c++ string to char array

C++ standard template library string A.K.A std::string was a novel concept back in the day(80s, 90s). Now we see every language be it Java or C# or Ruby contains an excellent implementation of string and 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 BSTR of COM era are just a sequence of characters with some meta data(length of string).

c++ string to char*

Since we know every std::string actually contains a char * buffer in the background, there must be some way to convert c++ string to char array.







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. 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 sue 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 C 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'm working as a full time freelance programmer through ODesk.com, I have a strong profile over there. Feel free to ping me if you need an Android app. Elance widget is given on top right of the page, for ODesk follow the link given below:


https://www.odesk.com/users/~012d73aa92fad47188

No comments:

Post a Comment

Feel free to talk back...