Does std::string contain null terminator?

mister picture mister · Aug 1, 2012 · Viewed 72.1k times · Source

Will the below string contain the null terminator '\0' ?

std::string temp = "hello whats up";

Thanks! :)

Answer

jahhaj picture jahhaj · Aug 1, 2012

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.