Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

std::string::front() in C++with Examples

  • Last Updated : 28 May, 2019

This function returns a direct reference to the first character of the string. This shall only be used on non-empty strings.
This can be used to access the first character of the string as well as to insert a character at the start of the string. Length of the string remains same after inserting a character, first character gets replaced by the new one.

Syntax

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
string str ("GeeksforGeeks");

Accessing first character
char first_char = str.front();

Inserting character at start of string
str.front() = '#';

Parameter: This function takes no parameter

Return value: A reference to the first character in the string



Exception: If the string is empty it shows undefined behavior.

Below examples illustrate the use of the above method:

Program 1:




// C++ program to demonstrate
// the use of the above method
  
#include <iostream>
  
// for std::string::front
#include <string>
  
using namespace std;
  
int main()
{
    string str("GeeksforGeeks");
  
    // Accessing first character of string
    char first_char = str.front();
  
    cout << "First character of string = "
         << first_char << endl;
  
    // Inserting a character at
    // the start of string
    str.front() = '#';
  
    cout << "New string = " << str << endl;
  
    return 0;
}
Output:
First character of string = G
New string = #eeksforGeeks



Program 2: It shows undefined behavior when the string is empty.




// C++ program to demonstrate
// the use of the above method
  
#include <iostream>
  
// for std::string::front
#include <string>
  
using namespace std;
  
int main()
{
    string str(""); // Empty string
  
    // trying to access first character
    // of an empty string
    char first_char = str.front();
  
    cout << "First character of string = "
         << first_char << endl;
  
    // Inserting a character at
    // the start of an empty string
    str.front() = '#';
  
    cout << "New string = " << str << endl;
  
    return 0;
}
Output:
First character of string = 
New string =

Reference: std::string::front()




My Personal Notes arrow_drop_up
Recommended Articles
Page :