C++ program to remove the last two characters from a string

In this tutorial, we’ll learn how to remove last two characters from the string in C++. In this program we’ll take string as an input from the user and the removed last two characters from the string will be the output. Here we follow many methods such as substr() and size() method, erase() method, resize() method.

How to remove the last two characters from a string in C++

To remove the last two characters from the string we use few methods. Let us see the detailed explanation of them in this tutorial.

1. substr() & size() method:

For getting a substring from any string we use substr() method. The syntax for getting substring is substr(pos,len). Here we use size() method to know the size of a string. To remove last two characters from the string we use the below line in the program.

cout<<“After removing last two characters : “<<inputs.substr(0, inputs.size() – 2)<<endl;

Here the position is 0 and the length is size() – 2 .

Program:

#include <iostream>
using namespace std;
int main()
{
    string inputs;
    cout<<"Enter the string : ";
    cin >> inputs;
    cout<<"After removing last two characters : "<<inputs.substr(0, inputs.size() - 2)<<endl;
}

Output:

Enter the string : morning
After removing last two characters : morni

2. erase() method

We use erase() method to remove the characters from the string because it can erase a character from the string based on its index. To remove the last two characters from the string we use below line in the program.

cout<<“After removing last two characters : “<<inputs.erase(inputs.size() – 2)<<endl;

Program:

#include <iostream>
using namespace std;
int main()
{
string inputs;
cout<<"Enter any string : "<<endl;
cin >> inputs;
cout<<"After removing last two characters : "<<inputs.erase(inputs.size() - 2);
}

Output:

Enter any string : afternoon
After removing last two characters : afterno

3. resize() method

resize() method is the most common used method to remove the characters from the string. It is used to resize any string to a particular length. The below program shows how the resize() method works. Since we need to remove last two characters from the string we should use the below line in the program.

inputs.resize(inputs.size() – 2); 

Program:

#include <iostream>
using namespace std;
int main()
{
    string inputs;
    cout<<"Enter the string from user : ";
    cin >> inputs;
    inputs.resize(inputs.size() - 2);
    cout<<inputs<<endl;
}

Output:

Enter the string from user : evening
eveni

 

For better understand of the above programs the kindly refer below links

Size of a string

How to remove digits from string

How to remove a particular character from a string in C++

Leave a Reply

Your email address will not be published. Required fields are marked *