Remove last character from C++ string
C++StringSubstringC++ Problem Overview
How can I remove last character from a C++ string?
I tried st = substr(st.length()-1);
But it didn't work.
C++ Solutions
Solution 1 - C++
Simple solution if you are using C++11. Probably O(1) time as well:
st.pop_back();
Solution 2 - C++
For a non-mutating version:
st = myString.substr(0, myString.size()-1);
Solution 3 - C++
if (str.size () > 0) str.resize (str.size () - 1);
An std::erase alternative is good, but I like the "- 1" (whether based on a size or end-iterator) - to me, it helps expresses the intent.
BTW - Is there really no std::string::pop_back ? - seems strange.
Solution 4 - C++
buf.erase(buf.size() - 1);
This assumes you know that the string is not empty. If so, you'll get an out_of_range
exception.
Solution 5 - C++
That's all you need:
#include <string> //string::pop_back & string::empty
if (!st.empty())
st.pop_back();
Solution 6 - C++
Solution 7 - C++
int main () {
string str1="123";
string str2 = str1.substr (0,str1.length()-1);
cout<<str2; // output: 12
return 0;
}
Solution 8 - C++
str.erase(str.begin() + str.size() - 1)
str.erase(str.rbegin())
does not compile unfortunately, since reverse_iterator
cannot be converted to a normal_iterator.
C++11 is your friend in this case.
Solution 9 - C++
With C++11, you don't even need the length/size. As long as the string is not empty, you can do the following:
if (!st.empty())
st.erase(std::prev(st.end())); // Erase element referred to by iterator one
// before the end
Solution 10 - C++
#include<iostream>
using namespace std;
int main(){
string s = "Hello";// Here string length is 5 initially
s[s.length()-1] = '\0'; // marking the last char to be null character
s = &s[0]; // using ampersand infront of the string with index will render a string from the index until null character discovered
cout<<"the new length of the string "<<s + " is " <<s.length();
return 0;
}
Solution 11 - C++
If the length is non zero, you can also
str[str.length() - 1] = '\0';