How to remove the last character from a string in C++

In this tutorial, we will learn how to remove the last character from a string in the C++ programing language

Remove the last character from a string in C++

#include <string>

    using namespace std;

   
    int main()

    {

        string abc = "CODESPEEDY";


        cout <<abc <<endl;


        abc.pop_back(); // Function of string class to remove the last character from string


        for (int i=0; i<abc.size(); i++) //for loop to print updated string

            cout <<abc[i];

        cout <<endl;


        return 0;

    }

In this code, we have used the “void pop_back()” function to remove the last character of the string. It is a function of string class provided in c++ language which has the void returning type which means it cannot return anything to any variable used in the main function.
The first two lines of code include libraries one of which is a string library that includes all string-related functions. The main() function starts with the declaration of the string, after which we have used the pop_back() function to remove the last character from the string, and at last with the help of for loop, we have given the updated string as output.

CODESPEEDY
CODESPEED

In this code we took the string “CODESPEEDY” and after using pop_back() function we are getting output as “CODESPEED”  and our last character “Y” has been removed from the string.

Leave a Reply

Your email address will not be published.