How to resize std::string to remove all null terminator characters?

Many ways to do this; but probably the one to me that seems to be most "C++" rather than C is:

str.erase(std::find(str.begin(), str.end(), '\0'), str.end());

i.e. Erase everything from the first null to the end.


You can do this:

buffer.erase(std::find(buffer.begin(), buffer.end(), '\0'), buffer.end());

Consider std::basic_string::erase has an overloading:

basic_string& erase( size_type index = 0, size_type count = npos );

A more succinct way:

buffer.erase(buffer.find('\0'));

You can use buffer.find('\0') instead of strlen(buffer.c_str())

Tags:

C++