Element Access

Accessing a character in a string is very easy and similar to element access in arrays.

We'll cover the following

The access to the elements of a string str is very convenient, because the string supports random access iterators. You can access with str.front() the first character and with str.back() the last character of the string. With str[n] and str.at(n) you get the n-th element by index.

The following table provides an overview.

Accessing the elements of a string #

Methods Example
str.front() Returns the first character of str.
str.back() Returns the last character of str.
str[n] Returns the n-th character of str. The string boundaries will not be checked.
str.at(n) Returns the n-th character of str. The string boundaries will be checked. If the boundaries are violated a std::out_of_range exception is thrown.

Get hands-on with 1000+ tech skills courses.