使用 std::string 的 empty() 方法可直接判断字符串是否为空,返回 true 表示空;2. 通过 size() 或 length() 判断长度是否为0也可实现,但 empty() 更推荐;3. 对于C风格字符串,需先检查指针是否为 nullptr,再判断首字符是否为 '\0';4. 使用 getline 读取后可用 empty() 检测用户是否仅输入回车。优先使用 empty(),C风格需注意指针安全。

在C++中判断字符串是否为空,主要取决于你使用的字符串类型。最常见的是 std::string 类型,也有C风格字符串(字符数组或指针)。下面介绍几种常用方法。
1. 使用 std::string 的 empty() 方法
这是推荐的方式,用于判断 std::string 是否为空:empty() 函数返回布尔值,如果字符串没有字符(长度为0),返回 true。
示例代码:
#include
#include iostream>
int main() {
std::string str;
if (str.empty()) {
std::cout
}
return 0;
}
2. 判断字符串长度是否为0
通过 size() 或 length() 方法获取字符串长度,判断是否为0:
if (str.size() == 0) {
// 字符串为空
}
// 或者
if (str.length() == 0) {
// 字符串为空
}
3. C风格字符串(char* 或字符数组)判空
对于C风格字符串,需要区分指针是否为 nullptr,以及字符串内容是否为空(即首字符是否为 '\0'):
char* cstr = nullptr;
// 判断指针是否为空或字符串是否为空
if (cstr == nullptr || *cstr == '\0') {
std::cout
}
4. 使用 getline 后判断
从输入读取字符串后,常需判断是否为空:
std::string input;
std::getline(std::cin, input);
if (input.empty()) {
std::cout
}
基本上就这些。对于 std::string,优先使用 empty() 方法;对于C风格字符串,要同时检查指针和内容。不复杂但容易忽略细节。











