C++ Standard Library C++ STL Library
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

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 MyString.

#include <iostream>
#include <string>

using namespace std;
 
int main (){
  string MyString = "HELLO";

  cout<<"The last character of MyString is: ";
  cout<<MyString.back();

  cout<<"\n\nAppend a string in the MyString.\n";
  MyString = MyString.append(" WORLD");

  cout<<"Now, The last character of MyString is: ";
  cout<<MyString.back();  
  return 0;
}

The output of the above code will be:

The last character of MyString is: O

Append a string in the MyString.
Now, The last character of MyString is: D

❮ C++ <string> Library

5