C++ std::string Accessing a character

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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


Got any C++ Question?