C++ String empty()的用法是什么

c++
1254
2023/11/7 18:05:45
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

C++中的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是非空字符串,所以str1.empty()返回false,而str2是空字符串,所以str2.empty()返回true。根据返回结果,可以采取相应的操作,如在字符串为空时执行某些逻辑。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c++中strtok函数的用途有哪些