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.
Author by
Putra Fajar Hasanuddin
Updated on July 09, 2022Comments
-
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 almost 10 yearsit will crash, if im only have 2 characters ?
-
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 almost 10 years
-
David Rodríguez - dribeas almost 10 yearsWhile 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 over 5 yearsthis 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 about 5 yearsThe 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 about 5 yearsyou can put the two condition in same while : as two condtion using AND or one while with if condition with break .