How to Remove Last Character From C++ String?
In C++, strings are stored as the std::string class objects. In this article, we will look at how to remove the last character from this C++ string object.
For Example,
Input: Hello! Geeks
Output: Hello! Geek
Remove the Last Character from a String in C++
To remove the last character from a string, we can use the pop_back() function which is used to pop the character that is placed at the last in the string and finally print the string after removal.
C++ Program to Remove the Last Character from a String
The below example demonstrates the use of the pop_back() function to remove the last character from the string.
// C++ program to remove the last character from a string.
#include <iostream>
#include <string>
using namespace std;
int main()
{
//declaring a string
string myString = "Hello,Geeks";
//printing string before deletion
cout << "Before deletion string is : " << myString << endl;
// Checking if the string is not empty before removing the last character
if (!myString.empty())
{
myString.pop_back();
}
//printing the string after deletion
cout << "String after removing the last character: " << myString << endl;
return 0;
}
Output
Before deletion string is : Hello,Geeks String after removing the last character: Hello,Geek
Note: pop_back() function works in-place meaning the modification is done in the original string only which results in a reduction of the size of the original string by one.
We can also use the erase() and resize() function to remove the last character from a string.