1. Home
  2. Computing & Technology
  3. C / C++ / C#

C++ Programming Tutorial - C++ Strings

By , About.com Guide

3 of 10

Working with C Strings Continued

But what about the other way? Just use the c_str() member function which returns a const char *. A string is an instance of a class that has many methods. This code from example 2 does that.

Download Example 2

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") ;
for (int i=0;i < s.length() ; i++)
{
  char c = s[ i ] ;
   cout << c << endl;
}
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.

On the next page : Working with C++ Strings

Explore C / C++ / C#
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. Working with C Strings Continued

©2009 About.com, a part of The New York Times Company.

All rights reserved.