Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

I'm using a std::string to interface with a C-library that requires a char* and a length field:

std::string buffer(MAX_BUFFER_SIZE, '\0');
TheCLibraryFunction(&buffer[0], buffer.size());

However, the size() of the string is the actual size, not the size of the string containing actual valid non-null characters (i.e. the equivalent of strlen()). What is the best method of telling the std::string to reduce its size so that there's only 1 ending null terminator character no explicit null terminator characters? The best solution I can think of is something like:

buffer.resize(strlen(buffer.c_str()));

Or even:

char buffer[MAX_BUFFER_SIZE]{};
TheCLibraryFunction(buffer, sizeof(buffer));
std::string thevalue = buffer;

Hoping for some built-in / "modern C++" way of doing this.

EDIT

I'd like to clarify the "ending null terminator" requirement I mentioned previously. I didn't mean that I want 1 null terminator explicitly in std::string's buffer, I was more or less thinking of the string as it comes out of basic_string::c_str() which has 1 null terminator. However for the purposes of the resize(), I want it to represent the size of actual non-null characters. Sorry for the confusion.

like image 623
void.pointer Avatar asked Mar 21 '18 15:03

void.pointer


People also ask

Does std :: string size include null terminator?

Actually, as of C++11 std::string is guaranteed to be null terminated. Specifically, s[s. size()] will always be '\0' .

How do you null terminate a string?

The null terminated strings are basically a sequence of characters, and the last element is one null character (denoted by '\0'). When we write some string using double quotes (“…”), then it is converted into null terminated strings by the compiler.

Does strlen return null terminator?

strlen(s) returns the length of null-terminated string s. The length does not count the null character.


2 Answers

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.

like image 50
UKMonkey Avatar answered Sep 28 '22 05:09

UKMonkey


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'));
like image 42
llllllllll Avatar answered Sep 28 '22 05:09

llllllllll