Skip to content
Related Articles

Related Articles

std::string::back() in C++ with Examples
  • Last Updated : 28 May, 2019

This function returns a direct reference to the last character of the string. This shall only be used on non-empty strings.
This can be used to access the last character of the string as well as to append a character at the end of the string. Length of the string remains unchanged after appending a character, last character of string gets replaced by the new one

Syntax

string str ("GeeksforGeeks");

Accessing last character
char end_char = str.back();

Appending character at end of string
str.back() = '#';

Parameter: This function takes no parameter

Return value: A reference to the last 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to demonstrate
// the use of the above method
  
#include <iostream>
  
// for std::string::back
#include <string>
  
using namespace std;
  
int main()
{
    string str("GeeksforGeeks");
  
    // Accessing last character of string
    char end_char = str.back();
  
    cout << "Last character of string = "
         << end_char << endl;
  
    // Appending a character to
    // the end of string
    str.back() = '#';
  
    cout << "New string = " << str << endl;
  
    return 0;
}

chevron_right


Output:

Last character of string = s
New string = GeeksforGeek#


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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 last character
    // of an empty string
    char end_char = str.back();
  
    cout << "Last character of string = "
         << end_char << endl;
  
    // Appending a character to
    // the end of an empty string
    str.back() = '#';
  
    cout << "New string = " << str << endl;
  
    return 0;
}

chevron_right


Output:

Last character of string = 
New string = ÉGÐ@·ùþ?aPé£Îý@?k¯ÃÿÿÿÿÿÿÿXé£Îýÿÿÿ
@Ï?¨Õ,Ä @Pé£ÎýÏ??Á±?ðÏ?Ø%Bð3ÇGøÂEÃ:µ# @Pé£ÎýI@Hé£Îýªÿ£Îý!P·Îýÿû?d@@8    ÀFà     @éé
éé©ê£ÎýÑÿ£Îý¹ê£Îý¾·ùþ?aDdCâ?gCx86_64

Reference: std::string::back()

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :