In this C++ tutorial, you will learn how to check if a given string is empty or not, with example programs.

Check if string is empty in C++

To check if a given string is empty or not in C++, you can use string empty() method or directly compare the given string to an empty string.

1. Check if string is empty using string empty() method in C++

In the following program, we will check if given string in str is empty or not using string empty() method.

Steps

  1. Given an input string in str.
  2. Use the empty() method of the string class to check if the string str is empty.
  3. If the string is empty, str.empty() will evaluate to true, indicating that the string contains no characters. Else the string is not empty. We can use a C++ if else statement for this step with str.empty() as condition.
  4. Inside the if-block, print a message to output that the string is empty.
  5. Inside the else-block, print a message to output that the string is not empty.

Program

main.cpp

</>
Copy
#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "";

    if (str.empty()) {
        cout << "The string is empty." << endl;
    } else {
        cout << "The string is not empty." << endl;
    }

    return 0;
}

Output

The string is empty.

Now, let us take a non-empty string in str, say “Hello World” and run the program.

main.cpp

</>
Copy
#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Hello World";

    if (str.empty()) {
        cout << "The string is empty." << endl;
    } else {
        cout << "The string is not empty." << endl;
    }

    return 0;
}

Output

The string is not empty.

2. Check if string is empty using string comparison in C++

In the following program, we will check if given string in str is empty or not using string comparison.

Steps

  1. Given an input string in str.
  2. Use the C++ Equal to operator == and pass the string str as left operand and the empty string "" as right operand.
  3. If the string is empty, str == "" will evaluate to true, indicating that the string contains no characters. Else the string is not empty. We can use a C++ if else statement for this step with str == "" as condition.
  4. Inside the if-block, print a message to output that the string is empty.
  5. Inside the else-block, print a message to output that the string is not empty.

Program

main.cpp

</>
Copy
#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "";

    if (str == "") {
        cout << "The string is empty." << endl;
    } else {
        cout << "The string is not empty." << endl;
    }

    return 0;
}

Output

The string is empty.

Conclusion

In this C++ Tutorial, we learned how to check if a given string is empty using string empty() method or string comparison, with examples.