Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 500
Putra Fajar Hasanuddin Avatar asked May 23 '14 16:05

Putra Fajar Hasanuddin


People also ask

How do you delete the first character in a string C?

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.

How do you remove the first and last character?

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

How do you get rid of the first and last character in a string C?

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.

How do you get rid of the last character in a string C?

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.


2 Answers

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.

like image 34
Hernán Avatar answered Oct 01 '22 12:10

Hernán


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

like image 152
Cameron Avatar answered Oct 01 '22 12:10

Cameron