C++ <string> - back() Function
The C++ string::back function returns a reference to the last character of the string. Please note that, Unlike the string::rbegin function, which returns the reverse iterator pointing to the last character, it returns the a direct reference to the same character of the string.
Syntax
char& back(); const char& back() const;
Parameters
No parameter is required.
Return Value
A reference to the last character of the string.
Time Complexity
Constant i.e, Θ(1).
Example:
In the example below, the string::back function is used to access the last character of the string str.
#include <iostream> #include <string> using namespace std; int main (){ string str = "HELLO"; cout<<"The last character of str is: "; cout<<str.back(); cout<<"\n\nAppend a string in the str.\n"; str = str.append(" WORLD"); cout<<"Now, The last character of str is: "; cout<<str.back(); return 0; }
The output of the above code will be:
The last character of str is: O Append a string in the str. Now, The last character of str is: D
❮ C++ <string> Library