C++判断string是否为空
代码之舞 发布于:2024-01-17 12:17:38
在C++中,可以使用以下方法来判断一个字符串是否为空:
- 使用empty()函数:
#include
#include using namespace std;
int main() { string str = \"Hello\";
if (str.empty()) {
cout << \"String is empty\" << endl;
} else {
cout << \"String is not empty\" << endl;
}
return 0;
}
2. 使用length()或size()函数:
```cpp
#include
#include
using namespace std;
int main() {
string str = \"Hello\";
if (str.length() == 0) {
cout << \"String is empty\" << endl;
} else {
cout << \"String is not empty\" << endl;
}
return 0;
}
- 使用比较运算符:
#include
#include using namespace std;
int main() { string str = \"Hello\";
if (str == \"\") {
cout << \"String is empty\" << endl;
} else {
cout << \"String is not empty\" << endl;
}
return 0;
}
这些方法都可以用来判断一个字符串是否为空。如果字符串为空,即长度为0,则可以认为字符串是空的。