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

C++ Programming Tutorial - C++ Strings

By , About.com Guide

8 of 10

Template String Functions Continued

Think of an iterator as a smart index. You can also change the value in an iterator by adding or subtracting ints.

string s="A jolly nice string";
string::iterator pos=s.begin() ;
pos += 2; // pos now points to j in jolly
In an STL container, the first element is accessed by the begin() method which returns an iterator. There's also one for end(). As the iterator is Random Access, it's possible to process the sequence in reverse and for that there a rbegin() and rend() as well. Using the string s in example 5, these two for loops print out the string forwards and backwards using an iterator and a reverse iterator.
// Forwards
for (string::iterator p = s.begin(); p<s.end(); p++)
  cout << *p;
cout << endl;
// Backwards
for ( string::reverse_iterator rp=s.rbegin() ; rp < s.rend(); rp++ )
  cout << *rp;
cout << endl;
This outputs
New Name sat on a wall.
.llaw a no tas emaN weN
Note Reverse iterators run from rbegin() to rend() even though they are iterating backwards. Remember, processing goes from begin to end, no matter which direction.

In the string class, there are template overloads of these functions : assign(), erase(), append(), replace(), and insert(). This example below, taken from example 7 shows erase() being used to remove the first part of a string.

string s("Humpty Dumpty sat on a wall.") ;
s2=s;
string::iterator parse = s2.begin()+ s2.find("Dumpty") ;
s2.erase(parse,parse+7) ;
cout << s2 << endl;

On the next page A small example of Text Processing.

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. Template String Functions Continued

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

All rights reserved.