温馨提示×

C++中string.empty怎么使用

小亿
217
2023-07-12 11:34:48
栏目: 编程语言

在C++中,string.empty()是用来判断一个字符串是否为空的函数。它返回一个bool值,如果字符串为空,则返回true,否则返回false。

以下是使用string.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不为空,所以str1.empty()返回false。而str2为空,所以str2.empty()返回true。

0