OneBite.Dev - Coding blog in a bite size

Check If A String Is Empty In C++

Code snippet for how to Check If A String Is Empty In C++ with sample and detail explanation

When programming in C++, you may encounter situations where you need to check if a string is empty. This article provides a clear and concise tutorial on how to carry out this task in C++.

Code Snippet: Checking if String is Empty

#include<iostream>
#include<string>

int main() {
    std::string str;
    if (str.empty()) {
        std::cout << "String is empty!";
    } else {
        std::cout << "String is not empty!";
    }

    return 0;
}

Code Explanation: Checking if String is Empty

In this C++ tutorial, we learn how to check if a string is empty using the string::empty() function. Here is our step-by-step explanation:

  1. We start off by including the iostream and string libraries. The iostream library allows us to perform input and output operations, while the string library allows us to use the string class and its associated functions.
#include<iostream>
#include<string>
  1. We move into our main() function where most of our code resides.
int main() {
  1. We declare a string variable named str. For our example, we are declaring an empty string.
std::string str;
  1. Now we come to the main part of our code. We’re using an if-else statement to check whether our string is empty or not. The str.empty() function returns true if the string is empty (i.e., it contains zero characters), and false otherwise.
if (str.empty()) {
   std::cout << "String is empty!";
} else {
   std::cout << "String is not empty!";
}

With this if-else statement, our code will print “String is empty!” if our string is empty and “String is not empty!” if it is not.

  1. Finally, our main function ends with a return 0 statement. This statement is a common convention that signifies that the program has successfully executed.
return 0;
}

And that’s it! You have successfully checked if a string is empty in C++.

c-plus-plus