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?
To remove the first character of a string, we can use the char *str = str + 1 in C. it means the string starts from the index position 1. Similarly, we can also use the memmove() function in C like this.
To remove the first and last characters from a string, call the slice() method, passing it 1 and -1 as parameters, e.g. str. slice(1, -1) .
Removing the first and last character In the example above, we removed the first character of a string by changing the starting point of a string to index position 1, then we removed the last character by setting its value to \0 . In C \0 means the ending of a string.
Every string in C ends with '\0'. So you need do this: int size = strlen(my_str); //Total size of string my_str[size-1] = '\0'; This way, you remove the last char.
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With