c语言判断字符串是否为全为字母
时间: 2023-09-24 16:06:06 浏览: 104
可以使用ctype.h头文件中的isalpha函数判断一个字符是否为字母,遍历字符串中的每个字符,如果存在一个不是字母的字符,则该字符串不全为字母。示例代码如下:
```c
#include <stdio.h>
#include <ctype.h>
int is_all_alpha(const char *str) {
while (*str != '\0') {
if (!isalpha(*str)) {
return 0;
}
str++;
}
return 1;
}
int main() {
char str1[] = "hello";
char str2[] = "123";
char str3[] = "Hello123";
printf("%s is all alpha? %d\n", str1, is_all_alpha(str1));
printf("%s is all alpha? %d\n", str2, is_all_alpha(str2));
printf("%s is all alpha? %d\n", str3, is_all_alpha(str3));
return 0;
}
```
输出结果为:
```
hello is all alpha? 1
123 is all alpha? 0
Hello123 is all alpha? 0
```
相关问题
c语言判断字符串是否为全为数字
可以使用isdigit()函数来判断字符串是否全为数字。isdigit()函数是C标准库中的函数,用于判断一个字符是否为数字。代码如下:
```c
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char str[] = "12345";
int i, len;
len = strlen(str);
for (i = 0; i < len; i++) {
if (!isdigit(str[i])) {
printf("该字符串不全为数字\n");
return 0;
}
}
printf("该字符串全为数字\n");
return 0;
}
```
在上面的代码中,我们首先使用strlen()函数获取字符串的长度,然后使用isdigit()函数判断每一个字符是否为数字。如果存在非数字字符,就输出“该字符串不全为数字”,并返回0;否则输出“该字符串全为数字”,并返回0。
c语言判断字符串是否为空
以下是两种C语言判断字符串是否为空的方法:
1. 判断字符串长度是否为0,如果为0则为空。
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "";
if (strlen(str) == 0) {
printf("字符串为空");
} else {
printf("字符串不为空");
}
return 0;
}
```
2. 判断字符串是否为NULL指针或者第一个字符是否为'\0',如果是则为空。
```c
#include <stdio.h>
#include <string.h>
int main() {
char *str = NULL;
if (str == NULL || str[0] == '\0') {
printf("字符串为空");
} else {
printf("字符串不为空");
}
return 0;
}
```
相关推荐
![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_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)
![](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)