C++ Accessing a character


Example

There are several ways to extract characters from a std::string and each is subtly different.

std::string str("Hello world!");

operator[](n)

Returns a reference to the character at index n.

std::string::operator[] is not bounds-checked and does not throw an exception. The caller is responsible for asserting that the index is within the range of the string:

char c = str[6]; // 'w'

at(n)

Returns a reference to the character at index n.

std::string::at is bounds checked, and will throw std::out_of_range if the index is not within the range of the string:

char c = str.at(7); // 'o'
C++11

Note: Both of these examples will result in undefined behavior if the string is empty.


front()

Returns a reference to the first character:

char c = str.front(); // 'H'

back()

Returns a reference to the last character:

char c = str.back(); // '!'