Remove last character from end of a string in C++
This post will discuss how to remove the last character from the end of the string in C++.
1. Using pop_back() function
The recommended approach is to use the pop_back() function introduced with C++11 to erase the last character of the string.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <string> int main() { std::string s = "C,C++,Java,"; if (!s.empty()) { s.pop_back(); } std::cout << s; return 0; } |
Output:
C,C++,Java
2. Using resize() function
The string class also provides a resize() function that can be used to resize the string to a particular length.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <string> int main() { std::string s = "C,C++,Java,"; if (!s.empty()) { s.resize(s.size() - 1); } std::cout << s; return 0; } |
Output:
C,C++,Java
3. Using erase() function
Another efficient solution is to use the erase() function of the string class. It has two variants. We can either:
1. Get the iterator to the last character and call the erase() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <string> int main() { std::string s = "C,C++,Java,"; if (!s.empty()) { s.erase(std::prev(s.end())); } std::cout << s; return 0; } |
Output:
C,C++,Java
2. Pass the last character’s index to the erase() function, which erases the last character.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <string> int main() { std::string s = "C,C++,Java,"; if (!s.empty()) { s.erase(s.size() - 1); } std::cout << s; return 0; } |
Output:
C,C++,Java
Please note that calling the substr() function on the string doesn’t modify the original string but constructs a new string. This can still work, as demonstrated here.
That’s all about removing the last character from the end of a string in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)