Copying non null-terminated unsigned char array to std::string

std::string has a constructor that takes a pair of iterators and unsigned char can be converted (in an implementation defined manner) to char so this works. There is no need for a reinterpret_cast. unsigned char u_array[4] = { ‘a’, ‘s’, ‘d’, ‘f’ }; #include <string> #include <iostream> #include <ostream> int main() { std::string str( u_array, … Read more

Using std::string_view with api that expects null-terminated string

I solved this problem by creating an alternate string_view class called zstring_view. It’s privately inherited from string_view and contains much of its interface. The principal difference is that zstring_view cannot be created from a string_view. Also, any string_view APIs that would remove elements from the end are not part of the interface or they return … Read more

What are null-terminated strings?

What are null-terminating strings? In C, a “null-terminated string” is a tautology. A string is, by definition, a contiguous null-terminated sequence of characters (an array, or a part of an array). Other languages may address strings differently. I am only discussing C strings. How are they different from a non-null-terminated strings? There are no non-null-terminated … Read more

Can a std::string contain embedded nulls?

Yes you can have embedded nulls in your std::string. Example: std::string s; s.push_back(‘\0’); s.push_back(‘a’); assert(s.length() == 2); Note: std::string‘s c_str() member will always append a null character to the returned char buffer; However, std::string‘s data() member may or may not append a null character to the returned char buffer. Be careful of operator+= One thing … Read more