如何通過(guò)string.empty控制程序流程

小樊
81
2024-10-16 19:59:22

在C++中,std::string::empty()函數(shù)用于檢查字符串是否為空。如果字符串為空,該函數(shù)返回true,否則返回false。你可以使用這個(gè)函數(shù)來(lái)控制程序流程,例如在條件語(yǔ)句中。以下是一個(gè)簡(jiǎn)單的示例:

#include <iostream>
#include <string>

int main() {
    std::string my_string;

    // 給字符串賦值
    my_string = "Hello, world!";

    // 檢查字符串是否為空
    if (my_string.empty()) {
        std::cout << "The string is empty." << std::endl;
    } else {
        std::cout << "The string is not empty." << std::endl;
    }

    // 根據(jù)字符串是否為空?qǐng)?zhí)行不同的操作
    if (my_string.empty()) {
        std::cout << "Do something for an empty string." << std::endl;
    } else {
        std::cout << "Do something for a non-empty string." << std::endl;
    }

    return 0;
}

在這個(gè)示例中,我們首先創(chuàng)建了一個(gè)名為my_string的空字符串。然后,我們使用std::string::empty()函數(shù)檢查字符串是否為空,并根據(jù)檢查結(jié)果輸出相應(yīng)的信息。最后,我們?cè)俅问褂脳l件語(yǔ)句根據(jù)字符串是否為空?qǐng)?zhí)行不同的操作。

0