Skip to main content

How To Think Like a Computer Scientist C++ Edition The Pretext Interactive Version

Section 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 ([ and ]) for this operation.
Listing 7.3.1. Take a look at this active code. We extract the character at index 1 from string fruit using [ and ].
The expression fruit[1] indicates that I want character number 1 from the string named fruit. The result is stored in a char named letter. When I output the value of letter, I get a surprise:
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 "banana" is b. The 1th letter (“oneth”) is a and the 2th (“twoeth”) letter is n .

Note 7.3.1.

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.
Listing 7.3.2. This active code accesses the first character in string fruit.

Checkpoint 7.3.1.

What would replace the “?” in order to access the letter “b” in the string below?
#include <iostream>
using namespace std;

int main() {
  string bake = "bake a cake!";
  char letter = bake[?];
}
  • Don’t forget that computer scientists do not start counting at 1!
  • Yes, this would access the letter "b".
  • This would access the letter "k".

Checkpoint 7.3.2.

What is printed when the code below is run?
#include <iostream>
using namespace std;

int main() {
  string lunch = "hello";
  string person = "deejay";
  lunch[0] = lunch[3];
  cout << lunch;
}
  • lunch
  • When we cout a string we print its content not its name.
  • jello
  • Carefully check which string(s) we are indexing into.
  • lello
  • Correct! We copy the ’l’ from position 3 of "hello" to position 0.
  • heljo
  • Consider which string(s) we are indexing into.

Checkpoint 7.3.3.

Checkpoint 7.3.4.

Construct a block of code that correctly prints the letter “a”.
You have attempted 1 of 6 activities on this page.