C++ Standard Library C++ STL Library

C++ <string> - front() Function



The C++ string::front function returns a reference to the first character of the string. Please note that, Unlike the string::begin function, which returns the iterator pointing to the first character, it returns the a direct reference to the same character of the string.

Syntax

char& front();
const char& front() const;

Parameters

No parameter is required.

Return Value

A reference to the first character of the string.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the string::front function is used to access the first character of the string str.

#include <iostream>
#include <string>

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

  cout<<"The first character of str is: ";
  cout<<str.front();

  cout<<"\n\nChange the first character of the string.\n";
  str[0] = 'C';

  cout<<"Now, The first character of str is: ";
  cout<<str.front();  
  return 0;
}

The output of the above code will be:

The first character of str is: H

Change the first character of the string.
Now, The first character of str is: C

❮ C++ <string> Library