判断字符数组是否为空
时间: 2023-11-03 14:06:07 浏览: 103
要判断一个字符数组是否为空,可以检查数组的长度是否为0。如果数组长度为0,那么它就是空的。以下是一个示例代码片段:
```cpp
#include <iostream>
bool isCharArrayEmpty(char* arr) {
return strlen(arr) == 0;
}
int main() {
char emptyArr[1] = "";
char nonEmptyArr[5] = "Hello";
if (isCharArrayEmpty(emptyArr)) {
std::cout << "The array is empty" << std::endl;
} else {
std::cout << "The array is not empty" << std::endl;
}
if (isCharArrayEmpty(nonEmptyArr)) {
std::cout << "The array is empty" << std::endl;
} else {
std::cout << "The array is not empty" << std::endl;
}
return 0;
}
```
在上述代码中,`isCharArrayEmpty`函数使用了`strlen`函数来计算字符数组的长度,并将其与0进行比较。如果长度为0,则返回`true`表示数组为空,否则返回`false`表示数组不为空。在`main`函数中,我们使用该函数来判断两个字符数组是否为空,并输出相应的结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)