Remove First and Last Character C++

188.3k Views Asked by At

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?

4

There are 4 best solutions below

4
On BEST ANSWER

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...

0
On

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.

4
On
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 ;
    } 
}
0
On

Simple answer:

str = str.substr(1,str.length()-2);

And to further what others were saying about @mhadhbi_issam code, here is a better approach:

void trimmed(std::string &str)
{
  int begI = 0,endI = str.length();
  if (endI == begI)
    return;
  std::string::iterator beg = str.begin();
  std::string::iterator end = str.end();
  end--;
  while (isspace(*beg) || isspace(*end))
  {
    if (isspace(*beg)) { beg++; begI++; }
    if (isspace(*end)) { end--; endI--; }
  }
  str = str.substr(begI,(endI-begI));
}