Suppose we have a string
std::string str; // some value is assigned
What is the difference between str.empty()
and str[0] == '\0'
?
Empty is a readonly field while "" is a const. This means you can't use String.
The following things are considered to be empty: "" (an empty string) 0 (0 as an integer)
An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .
An empty string is a String object with an assigned value, but its length is equal to zero. A null string has no value at all. A blank String contains only whitespaces, are is neither empty nor null , since it does have an assigned value, and isn't of 0 length.
string_variable[0]
is required to return the null character if the string is empty. That way there is no undefined behavior and the comparison still works if the string is truly empty. However you could have a string that starts with a null character ("\0Hi there"
) which returns true
even though it is not empty. If you really want to know if it's empty, use empty()
.
The difference is that if the string is empty then string_variable[0]
has undefined behavior; There is no index 0 unless the string is const
-qualified. If the string is const
qualified then it will return a null character.
string_variable.empty()
on the other hand returns true if the string is empty, and false if it is not; the behavior won't be undefined.
empty()
is meant to check whether the string/container is empty or not. It works on all containers that provide it and using empty
clearly states your intent - which means a lot to people reading your code (including you).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With