Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why setting null in the middle of std string doesn't have any effect

Tags:

c++

stdstring

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?

like image 280
Cheok Yan Cheng Avatar asked Jan 11 '11 02:01

Cheok Yan Cheng


3 Answers

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 *.

like image 147
Greg Hewgill Avatar answered Sep 24 '22 23:09

Greg Hewgill


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

like image 38
David Gelhar Avatar answered Sep 26 '22 23:09

David Gelhar


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

b.erase (3, b.length());
like image 26
EmeryBerger Avatar answered Sep 23 '22 23:09

EmeryBerger