Does std::string have a null terminator?
Will the below string contain the null terminator '\0'
?
std::string temp = "hello whats up";
Solution 1:
No, but if you say temp.c_str()
a null terminator will be included in the return from this method.
It's also worth saying that you can include a null character in a string just like any other character.
string s("hello");
cout << s.size() << ' ';
s[1] = '\0';
cout << s.size() << '\n';
prints
5 5
and not 5 1
as you might expect if null characters had a special meaning for strings.
Solution 2:
Not in C++03, and it's not even guaranteed before C++11 that in a C++ std::string is continuous in memory. Only C strings (char arrays which are intended for storing strings) had the null terminator.
In C++11 and later, mystring.c_str()
is equivalent to mystring.data()
is equivalent to &mystring[0]
, and mystring[mystring.size()]
is guaranteed to be '\0'
.
In C++17 and later, mystring.data()
also provides an overload that returns a non-const pointer to the string's contents, while mystring.c_str()
only provides a const
-qualified pointer.