Loading lessons...
Accessing String Characters
Accessing String Characters
Characters inside a string live at numbered positions called indexes. The first character sits at index 0.
Bracket access
string word = "Hello";
cout << word[0] << endl; // H
cout << word[1] << endl; // e
cout << word[4] << endl; // o
Indexes start at 0, so word[0] is the first character and word[4] is the last of a five-letter word.
Changing a character
word[0] = 'J';
cout << word << endl; // Jello
Single characters are written with single quotes: 'J'.
The .at() method
cout << word.at(1) << endl; // e
.at(index) does the same lookup, but it checks the bounds first.
Out-of-range risk
cout << word[99] << endl; // undefined behavior!
With [] there is no bound check - reading past the end is your problem. .at(99) throws an exception instead. In most learning code, keep your indexes in range and life stays simple.
TL;DR
- Indexing starts at 0:
word[0]is the first character. word[i] = 'x'changes a character (single quotes!)..at(i)is the bounds-checked version.- Reading out of range with
[]is undefined behavior.