Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

string

Suppose we have a string

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

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

like image 491
Pro Account Avatar asked Sep 27 '16 12:09

Pro Account


People also ask

What is the difference between string empty and?

Empty is a readonly field while "" is a const. This means you can't use String.

Is 0 an empty string?

The following things are considered to be empty: "" (an empty string) 0 (0 as an integer)

What does it mean if a string is empty?

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 .

Is blank and empty string the same?

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.


1 Answers

C++11 and beyond

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().


Pre-C++11

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.


Summary

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

like image 52
NathanOliver Avatar answered Sep 19 '22 16:09

NathanOliver