7.3. Extracting characters from a string¶
Strings are called "strings" because they are made up of a sequence, or string, of characters. Imagine a string of beads, where each character is a bead in the string.
Fig. 7.1 Characters in a string¶
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.
Take a look at the active code below. We extract the character
at index 1 from string fruit using [ and ].
1#include <iostream>
2#include <string>
3
4int main() {
5 std::string fruit = "orange";
6 char letter = fruit[1];
7 std::cout << letter;
8}
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:
r
r is not the first letter of "orange".
Unless you are a computer scientist.
Programmers (and most programming languages) always start
counting from zero.
The 0th letter (“zeroeth”) of "orange" is o.
The 1th letter (“oneth”) is r and the 2th (“twoeth”) letter is
a.
Note
In C++, indexing begins at 0!
If you want the zereoth letter of a string, then you have to put zero in the square brackets.
The active code below accesses the first character in string fruit.
1#include <iostream>
2#include <string>
3
4int main() {
5 string fruit = "orange";
6 char letter = fruit[0];
7 cout << letter << '\n';
8}
Q1
What would replace the "?" in order to access the letter "b" in the string below?
1#include <iostream>
2using namespace std;
3
4int main () {
5 string bake = "bake a cake!";
6 char letter = bake[?];
7}
Q2
What is printed when the code below is run?
1#include <iostream>
2using namespace std;
3
4int main () {
5 string lunch = "hello";
6 string person = "deejay";
7 lunch[0] = lunch[3];
8 cout << lunch;
9}
Q3
Click on each spot where a character in a string is accessed.
char letter =
cout << << '\n';
}Remember, square brackets [] are used to access a character in a string.
Remember, square brackets [] are used to access a character in a string.
Correct.
Remember, square brackets [] are used to access a character in a string.
Correct.
Q4
Construct a block of code that correctly prints the letter "a".
-
cout << x[7] << '\n'; -
cout << x[8] << '\n'; #distractor -
string x; -
x = "It is warm outside!"; -
x = "It is warm outside"