C++ String empty()实例讲解

   2025-02-20 3740
核心提示:C++的string类中的empty()函数用于判断字符串是否为空。如果字符串为空,即没有任何字符,则返回true;如果字符串不为空,则返回

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 emptystr2 is empty

在上面的示例中,str1不为空,因为它包含了字符"Hello"。而str2为空,因为它没有任何字符。

通过使用empty()函数,我们可以方便地判断一个字符串是否为空,从而根据需要执行相应的操作。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言