Why setting null in the middle of std string doesn

2019-05-14 06:54发布

问题:

Consider

#include <string>
#include <iostream>

int main()
{
    /*
    hello
    5
    hel
    3
    */
    char a[] = "hello";
    std::cout << a << std::endl;
    std::cout << strlen(a) << std::endl;
    a[3] = 0;
    std::cout << a << std::endl;
    std::cout << strlen(a) << std::endl;

    /*
    hello
    5
    hel o
    5
    */
    std::string b = "hello";
    std::cout << b << std::endl;
    std::cout << b.length() << std::endl;
    b[3] = 0;
    std::cout << b << std::endl;
    std::cout << b.length() << std::endl;

    getchar();

}

I expect std::string will behave identical to char array a. That's it, insert null character in the middle of the string, will "terminate" the string. However, it is not the case. Is my expectation wrong?

回答1:

A std::string is not like a usual C string, and can contain embedded NUL characters without problems. However, if you do this you will notice the string is prematurely terminated if you use the .c_str() function to return a const char *.



回答2:

No - std::strings are not NUL-terminated like C "strings"; the std::string records its length independently.



回答3:

@Lou is right: don't do that. Instead, do this:

b.erase (3, b.length());


回答4:

Yes, your expectation is wrong. std::string is meant to be different from C strings (e.g. not necessarily stored in consecutive memory / an array).

To duplicate the first section's behavior, try std::cout << b.c_str() instead of std::cout << b.



回答5:

I expect std::string will behave identical to char array a.

Why? Nothing in the documentation, anywhere, having to do with std::string says it does this.

My suggestion, stop treating like C++ as C plus some stuff.



标签: c++ stdstring