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

C++ Programming Tutorial - C++ Strings

By David Bolton, About.com

7 of 10

Templated String Functions in C++

In C++, the string class (i.e. std::string class) is a templated class which is actually the basic_string<> template class specialized for type char (and the 16 bit wchar_t in wstring). Specialized means it's instantiated for a specific type. We're still a few lessons away from templates in depth but as there are some STL functions in the string class, I'll mention them here.

Containers

Many classes in the STL (Standard Template Library) like list, vector and string are containers that store and provide sequential or direct access to a number of entities. The string class is a container that holds chars. All container classes access the contained elements safely and efficiently by using iterators.

A container class includes members such as

  • begin
  • clear
  • erase(iterator i)
  • erase(iterator first,iterator last)
  • find
and more. Using these and other methods requires a knowledge of iterators.

Iterators

An iterator is like a smart pointer that is used to walk through the elements of a container without knowing what the container holds. There are five iterator types in the STL but with strings we're only interested in the Random Access Iterator type. For efficiency, with strings an iterator is implemented a char *.

Iterators work with containers. The principle is that a container produces two iterators that define a sequence or subrange of values in the container. Then an STL algorithm (a function implemented as a function template) can be processed for each value in the sequence.

All iterators provide begin() and end() where begin() points to the start i.e. the first char, but end() always points one element past the last char.

Download Example 5

string s("Humpty Dumpty sat on a wall.");
string::iterator e = s.end()-1; // Points to period
cout << "Last Char is [" << (char *)e << "]" << endl;

On the next page Template Strings Continued

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. Templated String Functions in C++

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

All rights reserved.