7.3. Extracting characters from a string¶
Strings are called “strings” because they are made up of a sequence, or
string, of characters. The first operation we are going to perform on a
string is to extract one of the characters. C++ uses square brackets
]) for this operation.
Take a look at the active code below. We extract the character
at index 1 from string
fruit indicates that I want character number 1
from the string named
fruit. The result is stored in a
letter. When I output the value of
letter, I get a
a is not the first letter of
"banana". Unless you are a computer
scientist. For perverse reasons, computer scientists always start
counting from zero. The 0th letter (“zeroeth”) of
The 1th letter (“oneth”) is
a and the 2th (“twoeth”) letter is
In C++, indexing begins at 0!
If you want the the zereoth letter of a string, you have to put zero in the square brackets.
The active code below accesses the first character in string
Construct a block of code that correctly prints the letter “a”.