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

C++ Programming Tutorial - C++ Strings

By David Bolton, About.com

4 of 10

Working with C++ Strings

A string can be anything up to a few gigabytes in size and is restricted by the available RAM. However for efficiency, the actual size is stored and the string is memory managed through the capacity() and reserve() functions. The current capacity of a string is given by capacity() and you can change it through reserve(). My experience is that reserve increases the capacity (if a larger value is used) but doesn't shrink it with a smaller value. Some compilers may actually shrink it but it isn't guaranteed. The actual length of the string can be less than the capacity but never more. To change the strings actual length, not its capacity use resize().

Assigning and Appending Strings

Assignment can be done with = or the assign() member function. Both assign a constant string and can work with another string or a char * C String. However assign() can also take extra parameters for start and length.
const string s("Humpty Dumpty sat on a wall") ;
string s1,s2,s3,s4;
s1.assign(s,7,6) ; // Dumpty
cout << "s1= " << s1 << endl;
s2.assign("Once",2) ;
cout << "s2= " << s2 << endl;
s3="ZZY";
s3+= s1 += s2;
cout << "s3= " << s3 << endl;
s4="Once";
s4=s4.substr(2) ;
cout << "s4= " << s4 << end
This outputs
s1= Dumpty
s2= On
s3= ZZYDumptyOn

It looks similar to substr() but with the difference that the second parameter of assign() is the length not the start position.

substr("once",2); // ce
assign("once",2); // on

Emptying Strings

You can check if a string is empty with the empty) function. There is also a function clear() which empties a string, though it was never included in the library with Microsoft Visual C++ 6.0. (Not an oversight- just to do with the timing of including clear in the std library). You can however substitute erase() instead.

On the next page - An example with many functions

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

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

Easy ways to connect two computers for networking purposes. More >

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

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

All rights reserved.