C++ program to remove the last character from a string in different ways

Different ways in C++ to remove the last character from a string

In this tutorial, we will learn how to remove the last character of a string in different ways. Our program will take the string as an input from the user and print out the final result.

Method 1 : Using substr() and size() methods :

substr method is used to get one substring of a string in C++. We need to pass the start position and length of the substring. Below is its definition :substr(pos, len)

Here, pos is the position of the first character of the substring in the string and len is the length of the substring that we want. If you don’t provide the pos value, it will take 0 by default and if you don’t provide len , it will pick all the characters to the end.

In our case, we need to remove the last character from a string, i.e. we need a substring from the start position to the second last position.

size() method returns us the size of a string. We can use size() - 1 to get the length of the final string i.e. we will assign pos as 0 and len as size() - 1.

The below C++ program does that :

#include <iostream>
using namespace std;
int main()
{
    string input;
    cout<<“Enter a string :<<endl;
    cin >> input;
    cout<<“Removed last character :<<input.substr(0, input.size() - 1)<<endl;
}

Sample Output :

Enter a string :
world
Removed last character : worl

Enter a string :
onee
Removed last character : one

Method 2: Using resize :

resize() method is defined in the string class. It is used to resize one string to a particular length. It takes the new string length as argument and resizes the string to that length.

Below program explains how it works :

#include <iostream>
using namespace std;
int main()
{
    string input;
    cout<<“Enter a string :<<endl;
    cin >> input;
    input.resize(input.size() - 1);
    cout<<input<<endl;
}

It modifies the string *in place.*Following are some of the example outputs :

Enter a string :
World
Worl

Enter a string :
Helloo
Hello

Method 3 : Using erase() :

erase method can erase one character in a string based on its index. To remove the last character, we can pass the index of the last character of a string :

#include <iostream>
using namespace std;
int main()
{
    string input;
    cout<<“Enter a string :<<endl;
    cin >> input;
    input.erase(input.size() - 1);
    cout<<input<<endl;
}

pop_back() method is defined in C++11 . This method is designed to remove the last character of a string. It removes the last character and adjusts the string length accordingly.

#include <iostream>
using namespace std;
int main()
{
    string input;
    cout<<“Enter a string :<<endl;
    cin >> input;
    input.pop_back();
    cout<<input<<endl;
}

It will provide similar output as the above examples.