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:
- We start off by including the
iostream
andstring
libraries. Theiostream
library allows us to perform input and output operations, while thestring
library allows us to use the string class and its associated functions.
#include<iostream>
#include<string>
- We move into our
main()
function where most of our code resides.
int main() {
- We declare a string variable named
str
. For our example, we are declaring an empty string.
std::string str;
- 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 returnstrue
if the string is empty (i.e., it contains zero characters), andfalse
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.
- 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++.