Remove First and Last Character C++

Putra Fajar Hasanuddin picture Putra Fajar Hasanuddin · May 23, 2014 · Viewed 106.3k times · Source

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?

Answer

Cameron picture Cameron · May 23, 2014

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