C++ <string> - at() Function
The C++ string::at function returns a reference to the character of the string at the specified position. If the specified position is not within the bounds of valid characters in the string, the function throws an out_of_range exception.
Note: The string::at function produces the same result as string::operator[] function, except string::operator[] does not check the specified position against bounds of valid characters in the string.
Syntax
char& at (size_t n); const char& at (size_t n) const;
char& at (size_t n); const char& at (size_t n) const;
Parameters
n |
Specify position of the character in the string. |
Return Value
The character at the specified position in the string.
Time Complexity
Constant i.e, Θ(1).
Example:
In the example below, the string::at function returns a reference to the character of the string called str at the specified position.
#include <iostream> #include <string> using namespace std; int main (){ string str = "AlphaCodingSkills"; cout<<"The string contains:"; for(int i = 0; i < str.size(); i++) cout<<" "<<str.at(i); return 0; }
The output of the above code will be:
The string contains: A l p h a C o d i n g S k i l l s
❮ C++ <string> Library