String Access
There are four methods for accessing individual characters, two using the [] operator 0, and two using the at() method:
reference operator[](size_type pos); const_reference operator[](size_type pos) const; reference at(size_type n); const_reference at(size_type n) const;
The first operator[]() method allows you to access an individual element of a string using array notation; it can be used to retrieve or alter the value. The second operator[]() method can be used with const objects, and it can be used only to retrieve the value:
string word("tack"); cout << word[0]; // display the t word[3] = t'; // overwrite the k with a t const ward("garlic"); cout << ward[2]; // display the r
The at() methods provide similar access, except ...
Get The Waite Group's C++ Primer Plus, Third Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.