Accessing a character

suggest change

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 ensuring 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'

Note: If the string is empty, str[6] is undefined behavior, while str.at(7) throws std::out_of_range. front() and back() are also undefined behavior on an empty string. Since C++11, operator[] with an index equal to size() is defined and refers to a charT() object that must not be modified; an index greater than size() is still undefined behavior.

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(); // '!'

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents