C++ String empty()实例讲授
C++的string类中的empty()函数用于判断字符串是否是为空。如果字符串为空,即没有任何字符,则返回true;如果字符串不为空,则返回false。
下面是一个示例代码,演示了empty()函数的用法:
#include
#include
int main() {
std::string str1 = "Hello";
std::string str2 = "";
if (str1.empty()) {
std::cout << "str1 is empty" << std::endl;
} else {
std::cout << "str1 is not empty" << std::endl;
}
if (str2.empty()) {
std::cout << "str2 is empty" << std::endl;
} else {
std::cout << "str2 is not empty" << std::endl;
}
return 0;
}
输出结果为:
str1 is not empty
str2 is empty
在上面的示例中,str1不为空,由于它包括了字符"Hello"。而str2为空,由于它没有任何字符。
通过使用empty()函数,我们可以方便地判断一个字符串是否是为空,从而根据需要履行相应的操作。
TOP