Mental Model
A string is a sequence of characters you can look at one by one from start to end.
Analogy: Like reading a sentence letter by letter to understand or find a specific letter.
S -> t -> r -> i -> n -> g -> \0 ā
S -> t -> r -> i -> n -> g -> \0 ā
c -> a -> t -> \0 ā
c -> a -> t -> \0 ā
c -> a -> t -> \0
āc -> a -> t -> \0
āc -> a -> t -> \0
āc\na\nt\n
#include <iostream> #include <string> void printChars(const std::string& str) { for (size_t i = 0; i < str.size(); ++i) { std::cout << str[i] << '\n'; // print current character } } int main() { std::string input = "cat"; printChars(input); return 0; }
for (size_t i = 0; i < str.size(); ++i) {std::cout << str[i] << '\n';for (size_t i = 0; i < str.size(); ++i) {
for (size_t i = 0; i < str.size(); ++i) {
str[i] do when str is a string in C++?str[i] accesses the character at position i.str[i] returnsi without modifying the string.str in C++?str.length() - 1. So loop must run while i < str.length().i < str.length() starting from 0, which correctly covers all characters without going out of bounds.std::string s = "hello";
for (int i = 0; i < s.length(); i++) {
if (s[i] == 'l') {
std::cout << i << " ";
}
}str:for (int i = 0; i <= str.length(); i++) {
std::cout << str[i];
}i <= str.length(), which means it tries to access str[str.length()].str.length() - 1. Accessing str[str.length()] is out-of-bounds and causes undefined behavior.str, how can you create a new string containing only the vowels from str using traversal and character access in C++?str using indexing.Pass the test and this pattern moves unknown