c++

C++中string.empty的用法是什么

小亿
109
2023-12-23 09:43:11
栏目: 编程语言

在C++中,string.empty()是一个成员函数,用于检查一个字符串是否为空。它返回一个bool值,如果字符串为空则返回true,否则返回false。

使用示例:

#include <iostream>
#include <string>

int main() {
    std::string str1 = "";
    std::string str2 = "Hello";

    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 empty
str2 is not empty

在上面的示例中,我们使用empty()函数检查了两个字符串的状态。str1为空字符串,所以empty()函数返回true,而str2不为空,所以empty()函数返回false。

0
看了该问题的人还看了