remove last letter in string c++
To remove the last letter in a string in C++, you can follow these steps:
Declare a string variable: Start by declaring a string variable and assigning the desired string to it. For example,
std::string str = "Hello";
.Get the length of the string: Use the
length()
orsize()
function to get the length of the string. For example,int len = str.length();
.Remove the last character: To remove the last character from the string, you can use the
erase()
function. Pass the index of the last character as the starting point and specify a count of 1. For example,str.erase(len - 1, 1);
.Print or use the modified string: Finally, you can print or use the modified string as needed. For example,
std::cout << str;
.
Here is an example that puts all the steps together:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello";
int len = str.length();
str.erase(len - 1, 1);
std::cout << str;
return 0;
}
This code will output "Hell" because the last letter 'o' has been removed from the original string "Hello".