Game Development Reference
In-Depth Information
The methods in Table
13-2
show how you can append data to the end of an existing string. Each
of the types also have a corresponding overloaded
+=
operator, meaning that you can append to a
string using code that resembles a normal arithmetic equation.
The same types are also supported by the
assign
methods. Where
append
adds the supplied text to
the end of your strings,
assign
replaces the data in your
string
with the supplied text. The
assign
methods are also implemented as the overloaded = operators.
It's also possible to access individual characters in our string using the array operator.
str[0]
would
return the first character of a given
string
. It's rare that you'll want to access string data in this
manner, and the next section covers a more useful way of traversing string data.
Accessing String Data Through Iterators
Iterators are going to become second nature to you as you work with the STL. All of the data
containers supplied by the STL use the iterator pattern to supply you access to their individual
elements. In the case of a string, an iterator gives access to a single character in your string. You can
use iterators to traverse the data structure forward and backward. Listing 13-6 shows how you can
loop over a string and print out the individual characters using iterators.
Listing 13-6. Looping over a
String
void StringIterators()
{
using namespace std;
string myString{ "This is my string!" };
for (string::iterator iter = myString.begin(); iter != myString.end(); ++iter)
{
cout << *iter << endl;
}
}
The type for a
string iterator
is
string::iterator
. The methods
begin
and
end
return iterators that
represent the beginning and end of our string data. The iterator we declare is named
iter
and we
can move to the next element in the string using the increment operator. You can see that we must
dereference
iter
to gain access to the data that is contained at the current position in the
string
.
It's also possible to decrement
string::iterator
and you can see this in action in Listing 13-7.
Listing 13-7.
Decrementing string::iterator
for (string::iterator iter = myString.end()-1; iter != myString.begin(); --iter)
{
cout << *iter << endl;
}
A better way to move backward through a
string
from end to beginning is to use
string::reverse_
iterator
, which you can see in Listing 13-8.