How to remove first and last character from std::string, I am already doing the following code.
But this code only removes the last character
m_VirtualHostName = m_VirtualHostName.erase(m_VirtualHostName.size() - 1)
How to remove the first character also?
This question is related to
c++
string
stdstring
erase-remove-idiom
Well, you could erase()
the first character too (note that erase()
modifies the string):
m_VirtualHostName.erase(0, 1);
m_VirtualHostName.erase(m_VirtualHostName.size() - 1);
But in this case, a simpler way is to take a substring:
m_VirtualHostName = m_VirtualHostName.substr(1, m_VirtualHostName.size() - 2);
Be careful to validate that the string actually has at least two characters in it first...
My BASIC interpreter chops beginning and ending quotes with
str->pop_back();
str->erase(str->begin());
Of course, I always expect well-formed BASIC style strings, so I will abort with failed assert
if not:
assert(str->front() == '"' && str->back() == '"');
Just my two cents.
std::string trimmed(std::string str ) {
if(str.length() == 0 ) { return "" ; }
else if ( str == std::string(" ") ) { return "" ; }
else {
while(str.at(0) == ' ') { str.erase(0, 1);}
while(str.at(str.length()-1) == ' ') { str.pop_back() ; }
return str ;
}
}
Source: Stackoverflow.com