< Previous | Contents | Next >

Indexing a string Object

A string object stores a sequence of char values. You can access any individual char value by providing an index number with the subscripting operator ([]). Thats what I do next:

cout << "The character at position 0 is: " << phrase[0] << "\n\n";

The first element in a sequence is at position 0. In the previous statement, phrase

[0] is the character G. And because counting begins at 0, the last character in the string object is phrase[11], even though the string object has 12 characters in it.


Tra p

image

It’s a common mistake to forget that indexing begins at position 0. Remember, a string object with n characters in it can be indexed from position 0 to position n 1.

image


Not only can you access characters in a string object with the subscripting operator, but you can also reassign them. Thats what I do next:

phrase[0] = ’L’;

I change the first character of phrase to the character L, which means phrase

becomes "Lame Over!!!"


Tra p

image

Cþþ compilers do not perform bounds checking when working with string objects and the subscripting operator. This means that the compiler doesn’t check to see whether you’re attempting to access an element that doesn’t exist. Accessing an invalid sequence element can lead to disastrous results because it’s possible to write over critical data in your computer’s memory. By doing this, you can crash your program, so take care when using the subscripting operator.

image