C++ - Strings: Access
Overview
Estimated time: 15–20 minutes
Read and modify characters by index, and iterate over strings safely.
Learning Objectives
- Use operator[] vs at() and know the bounds-checking difference.
- Iterate with range-for and iterators.
Prerequisites
Examples
#include <string>
#include <iostream>
int main(){
std::string s = "hello";
s[0] = 'H';
try { s.at(10) = '!'; }
catch(const std::out_of_range&){ std::cout << "OOR"; }
for(char ch : s) std::cout << ch;
}
Common Pitfalls
- operator[] has undefined behavior on out-of-range access; prefer at() when safety matters.