c++

C++ String empty()实例讲解

小云
97
2023-09-28 09:48:35
栏目: 编程语言

C++的string类中的empty()函数用于判断字符串是否为空。如果字符串为空,即没有任何字符,则返回true;如果字符串不为空,则返回false。

下面是一个示例代码,演示了empty()函数的用法:

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

0
看了该问题的人还看了