新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

C++ String empty()实例讲解

发布时间:2023-09-28 09:48:35

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()函数,我们可以方便地判断一个字符串是否是为空,从而根据需要履行相应的操作。