Open In App

How to Check if a String is Empty in C++?

Last Updated : 01 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, strings are the sequence of characters that are stored as std::string class objects. In this article, we will learn how to check if a string is empty in C++

Example

Input: str1="Hello! Geek" ; str2=""

Output: 
str1 is not empty
str2 is empty

Checking if the String is Empty in C++

To check for an empty string we can use the std::string::empty() function because what the empty function does is it checks for the length of a string and if the string is empty, it returns true, otherwise, it returns false.

C++ Program to Check for Empty String

The below example demonstrates the use of the empty function to check for empty string.

C++




// C++ program to check for empty string
  
#include <iostream>
#include <string>
using namespace std;
  
int main()
{
  
    // declaring teo strings
    string str1 = "Hello! Geek";
    string str2 = "";
    // checking if the given string is empty or not
    if (str1.empty()) {
        // string is found empty
        cout << "str1 is empty" << endl;
    }
    else {
        cout << "str1 is not empty" << endl;
    }
  
    if (str2.empty()) {
        cout << "str2 is empty" << endl;
    }
    else {
        cout << "str2 is not empty" << endl;
    }
  
    return 0;
}


Output

str1 is not empty
str2 is empty

We can also use compare() and size() functions to check if string is empty.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads