string s("Hello World") ;
const char * p = s.c_str() ;
char * p2 = new char[ s.length()+1];
strcpy(p2,s.c_str()) ;
cout << s.data() << endl;
delete [] p2;
Note You may also see size() used instead of length() One is an alias of the other. In the STL, size() is generally used to count the number of elements.
The first pointer p points to the char * pointer whereas p2 allocates enough memory for the string plus a terminating zero then copies it. The string length() function returns the length of the string. The last line outputs the results of the data() call. This returns a const char * pointer to the internal data, like c_str() but does not append a terminating zero.
Where is the text held in the string stored?
It's managed internally by the class and you can access it through data().
Use of copy() instead of data()
The data() function returns a char * to the internal string representation as an array of char, but char() copies characters to the target. Neither of these two functions adds a terminating '\0' so they cannot be used as a C string without appending a '\0'.Manipulating Strings
The string class comes with a number of useful methods. Accessing individual characters is as easy as any array.string s("Humpty Dumpty sat on a wall") ;If you want to do this safely use s.at(i) instead which does a range check to make sure you're not indexing past the start or end. s[-1] didn't generate an exception but s.at(-1) generated an "out of range" exception.
for (int i=0;i < s.length() ; i++)
{
char c = s[ i ] ;
cout << c << endl;
}
On the next page : Working with C++ Strings

