c++stringstdstringerase-remove-idiom

Remove First and Last Character C++


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?


Solution

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