#include#include using namespace std; int main() { string str1 = ""; string str2 = "Hello world!"; // Example 1: Check if a string is null or empty if (str1.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; }
str1 is empty. str2 is not empty.
#include#include using namespace std; int main() { string str1 = ""; string str2 = "Hello world!"; string str3; // Example 2: Check if a string is null or empty and assign a default value str3 = str1.empty() ? "default value" : str1; cout << "str3: " << str3 << endl; str3 = str2.empty() ? "default value" : str2; cout << "str3: " << str3 << endl; return 0; }
str3: default value str3: Hello world!This method belongs to the C++ Standard Library.