溫馨提示×

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

c++
小億
308
2023-10-21 18:05:45
欄目: 編程語言

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。根據返回結果,可以采取相應的操作,如在字符串為空時執行某些邏輯。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女