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

前端 未结 6 1637
予麋鹿
予麋鹿 2021-02-11 12:15

Suppose we have a string

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

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

6条回答
  •  名媛妹妹
    2021-02-11 12:22

    You want to know the difference between str.empty() and str[0] == '\0'. Lets follow the example:

    #include
    #include
    using namespace std;
    
    int main(){
    string str, str2; //both string is empty
    str2 = "values"; //assigning a value to 'str2' string
    str2[0] = '\0'; //assigning '\0' to str2[0], to make sure i have '\0' at 0 index
    
    if(str.empty()) cout << "str is empty" << endl;
    else cout << "str contains: " << str << endl;
    
    if(str2.empty()) cout << "str2 is empty" << endl;
    else cout << "str2 contains: " << str2 << endl;
    
    return 0;
    }
    

    Output:

    str is empty
    str2 contains: alues
    

    str.empty() will let you know the string is empty or not and str[0] == '\0' will let you know your strings 0 index contains '\0' or not. Your string variables 0 index contains '\0' doesn't mean that your string is empty. Yes, only once it can be possible when your string length is 1 and your string variables 0 index contains '\0'. That time you can say that, its an empty string.

提交回复
热议问题