C++ Standard Library C++ STL Library

C++ <string> - empty() Function



The C++ string::empty function is used to check whether the string is empty or not. It returns true if the length of the string is zero, else returns false.

Syntax

bool empty() const;
bool empty() const noexcept;

Parameters

No parameter is required.

Return Value

true if the size of the string is zero, else returns false.

Time Complexity

Constant i.e, Θ(1)

Example:

In the example below, the string::empty function is used to check whether the string is empty or not.

#include <iostream>
#include <string>

using namespace std;
 
int main (){
  string str1 = "Hello World!.";
  string str2 = "";

  cout<<"String is: "<<str1<<"\n";
  cout<<"String length: "<<str1.length()<<"\n";
  cout<<"Is it empty?: "<<str1.empty()<<"\n\n";

  cout<<"String is: "<<str2<<"\n";
  cout<<"String length: "<<str2.length()<<"\n";
  cout<<"Is it empty?: "<<str2.empty();
  return 0;
}

The output of the above code will be:

String is: Hello World!.
String length: 13
Is it empty?: 0

String is: 
String length: 0
Is it empty?: 1

❮ C++ <string> Library