Remove First and Last Character C++

132,963

Solution 1

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

Solution 2

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.

Share:
132,963
Putra Fajar Hasanuddin
Author by

Putra Fajar Hasanuddin

Updated on July 09, 2022

Comments

  • Putra Fajar Hasanuddin
    Putra Fajar Hasanuddin almost 2 years

    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?

  • Putra Fajar Hasanuddin
    Putra Fajar Hasanuddin almost 10 years
    it will crash, if im only have 2 characters ?
  • Cameron
    Cameron almost 10 years
    @Putra: Yes. C++ is not particularly friendly that way ;-) Edit: No, I misread your comment. It will crash if you have less than two characters (0 or 1).
  • Appleshell
    Appleshell almost 10 years
    @PutraFajarHasanuddin It will when you have no or 1 character in the string. It's documented here. Only execute the second line when size() returns at least 1.
  • David Rodríguez - dribeas
    David Rodríguez - dribeas almost 10 years
    While the substr looks cleaner in code it will trigger an additional memory allocation (which might or not be important). Also the first erase might be simpler if stated as: str.erase(str.end()-1); str.erase(str.begin());
  • Mhadhbi issam
    Mhadhbi issam over 5 years
    this function make the string trimmed , it is equivalent to QString::trimmed(QString) , it delete the white space from end and front , do whatever it need to modify it to make it do the job ...............
  • Brandlingo
    Brandlingo about 5 years
    The while-loops (especially the front one) will make this quite inefficient. Search for the last/first blank and execute a single erase for each.
  • Mhadhbi issam
    Mhadhbi issam about 5 years
    you can put the two condition in same while : as two condtion using AND or one while with if condition with break .