How to Remove Last Character From C++ String?
Last Updated :
01 Feb, 2024
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++
#include <iostream>
#include <string>
using namespace std;
int main()
{
string myString = "Hello,Geeks" ;
cout << "Before deletion string is : " << myString << endl;
if (!myString.empty())
{
myString.pop_back();
}
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.
Share your thoughts in the comments
Please Login to comment...