
Think together · Start with a story
A girl wants to count how many A's are in BANANA. The robot moves from left to right and adds a mark each time it finds one.
Break down the process
- Visit each positionRead one character
- Check itDoes it match?
- UpdateAdd to the count
You can traverse a string to check and count its elements one by one.
01How do you visit each character?
Use an index to move through the string from the beginning to the end:
std::string s = "cat";
for (std::size_t i = 0; i < s.size(); i++) {
std::cout << s[i] << ' ';
}
02You can also use a range-based for loop
for (char c : s) {
std::cout << c << ' ';
}
The loop puts each character unit into c in turn.
03How do you count occurrences of a character?
int count = 0;
for (char c : s) {
if (c == 'a') {
count++;
}
}
Each time the loop finds an 'a', it increases the counter by 1.
04How do you change a character in a string?
std::string s = "cat";
s[0] = 'b';
After the change, the string is "bat".
You can also traverse it using references:
for (char& c : s) {
// You can change c directly
}
05How do you find a substring?
std::string s = "computer";
auto pos = s.find("put");
If the substring is found, pos is its first position. If it is not found, the result is std::string::npos.
06Why can you not traverse UTF-8 Chinese this way?
If the string contains UTF-8 Chinese or emoji:
std::string s = "你好";
Traversing with char usually reads one UTF-8 encoded byte at a time, not one complete Chinese character.
07Can you go out of bounds when traversing a string?
Yes. For a non-empty string, valid indexes are still:
Do not use s[s.size()] as an ordinary character position.
Use s.at(i) if you want runtime bounds checking.
What you have learned
- You can traverse
std::stringusing indexes or a range-based for loop. - Traversal can be used for counting, searching, and modifying.
findcan search for a substring.- String indexes can go out of bounds too, so check them.
- With UTF-8, traversing by char reads bytes, not necessarily complete Unicode characters.
Next: What Problems Can Arrays Help Us Solve?
Your turn to try
In AaA, will counting only uppercase A's give you 3?
Ready? Open to see the explanation
You get 2. The lowercase a in the middle is different from uppercase A. To count both, you must explicitly adjust the rule.