How do you delete the last element of a string in C++? Thnx!
Printable View
How do you delete the last element of a string in C++? Thnx!
http://cplusplus.com/reference/string/string/erase.html
http://cplusplus.com/reference/string/string/size.html
If you use size as an argument, you can delete the last character in the string. Not sure how, never used the erase() function.
You can erase the last char, or truncate the length of the string.
Todd
Output:Code:#include <iostream>
#include <string>
int main ( void )
{
std::string str("Hello World!");
std::cout << "Before: \"" << str << '\"' << std::endl;
str.resize(str.size()-1);
std::cout << "After : \"" << str << '\"' << std::endl;
return 0;
}
Code:Before: "Hello World!"
After : "Hello World"
just for reference:
http://cppreference.com/cppstring/index.html
std::string has an erase function that can remove a character from a string.
deleting the last element would be like so:
Code:
std::string str = "hello";
str.erase(str.end() - 1);
std::cout << str; // "hell"