There are several ways to extract characters from a std::string
and each is subtly different.
std::string str("Hello world!");
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'
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: Both of these examples will result in undefined behavior if the string is empty.
Returns a reference to the first character:
char c = str.front(); // 'H'
Returns a reference to the last character:
char c = str.back(); // '!'