Difference between string.empty and string[0] == '\0'

前端 未结 7 2223
迷失自我
迷失自我 2021-02-11 11:43

Suppose we have a string

std::string str; // some value is assigned

What is the difference between str.empty() and str[0] =

7条回答
  •  无人及你
    2021-02-11 12:32

    C++ string has the concept of whether it is empty or not. If the string is empty then str[0] is undefined. Only if C++ string has size >1, str[0] is defined.

    str[i] == '\0' is a concept of the C-string style. In the implementation of C-string, the last character of the string is '\0' to mark the end of a C-string.
    For C-string you usually have to 'remember' the length of your string with a separate variable. In C++ String you can assign any position with '\0'.

    Just a code segment to play with:

    #include 
    #include 
    
    using namespace std;
    
    int main(int argc, char* argv[]) {
       char str[5] = "abc";
       cout << str << " length: " << strlen(str) << endl;
       cout << "char at 4th position: " << str[3] << "|" << endl;
       cout << "char at 5th position: " << str[4] << "|" << endl;
       str[4]='X'; // this is OK, since Cstring is just an array of char!
       cout << "char at 5th position after assignment: " << str[4] << "|" << endl;
       string cppstr("abc");
       cppstr.resize(3);
       cout << "cppstr: " << cppstr << " length: " << cppstr.length() << endl;
       cout << "char at 4th position:" << cppstr[3] << endl;
       cout << "char at 401th positon:" << cppstr[400] << endl;
       // you should be getting segmentation fault in the
       // above two lines! But this may not happen every time.
    
       cppstr[0] = '\0';
       str[0] = '\0';
       cout << "After zero the first char. Cstring: " << str << " length: " << strlen(str) << " | C++String: " << cppstr << " length: " << cppstr.length() << endl;
       return 0;
    }
    

    On my machine the output:

    abc length: 3
    char at 4th position: |
    char at 5th position: |
    char at 5th position after assignment: X|
    cppstr: abc length: 3
    char at 4th position:
    char at 401th positon:?
    After zero the first char. Cstring:  length: 0 | C++String: bc length: 3
    

提交回复
热议问题