可以尝试不用ctype.h文件进行编写吗
时间: 2024-01-14 11:04:07 浏览: 93
是的,我们也可以不使用 `ctype.h` 头文件中的函数来实现统计字符串内数字字符的个数的程序。下面是一个不使用 `ctype.h` 的版本:
```c
#include <stdio.h>
int main() {
char str[100];
int count = 0;
printf("请输入一个字符串:");
fgets(str, 100, stdin);
for(int i = 0; str[i] != '\0'; i++) {
if(str[i] >= '0' && str[i] <= '9') {
count++;
}
}
printf("\n字符串中数字字符的个数为:%d\n", count);
return 0;
}
```
这个版本的程序中,我们使用了 ASCII 码来判断字符是否为数字字符。在 ASCII 码表中,数字字符 '0' 到 '9' 的 ASCII 码值分别是 48 到 57,因此我们可以使用 `str[i] >= '0' && str[i] <= '9'` 来判断一个字符是否为数字字符。如果是,则计数器加一。最后输出统计结果。
相关问题
不用ctype.h头文件实现上述问题
以下是一个不依赖ctype.h头文件的C语言程序,用于统计一个文本文件中的字母、数字和其他字符的数量:
```c
#include <stdio.h>
int main() {
FILE *fp;
char ch;
int digits = 0, letters = 0, others = 0;
fp = fopen("filename.txt", "r");
if (fp == NULL) {
printf("无法打开文件\n");
return 1;
}
while ((ch = fgetc(fp)) != EOF) {
if (ch >= '0' && ch <= '9') {
digits++;
} else if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
letters++;
} else {
others++;
}
}
fclose(fp);
printf("数字:%d\n", digits);
printf("字母:%d\n", letters);
printf("其他:%d\n", others);
return 0;
}
```
解释:
1. 引入stdio.h头文件,用于文件操作。
2. 定义一个指向文件的指针fp,以及三个变量digits、letters、others,分别用于记录数字、字母和其他字符的数量。
3. 打开一个名为filename.txt的文件,以只读模式打开。
4. 判断文件是否打开成功,如果失败,输出错误信息并返回1。
5. 通过fgetc函数逐个读取文件中的字符,直到文件结束。
6. 判断读取到的字符属于哪一类:如果是数字(ASCII码为48~57),则digits加1;如果是字母(ASCII码为65~90和97~122),则letters加1;否则,others加1。
7. 关闭文件。
8. 输出统计结果。
9. 返回0,表示程序执行成功。
不用#include <ctype.h> 实现
如果你不想使用`<ctype.h>`库来检查字符是否为小写字母,可以手动编写一段代码来判断。下面是一个不需要`ctype.h`的版本:
```c
#include <stdio.h>
#include <string.h>
// 定义计数小写字母的函数
int CountLowerCase(char* str) {
int count = 0;
for (; *str != '\0'; str++) { // 遍历字符串直到结束
if (*str >= 'a' && *str <= 'z') { // 判断是否是小写字母
count++;
}
}
return count; // 返回小写字母的总数
}
int main() {
char s1[10000], s2[10000];
printf("请输入第一个字符串(小写字符计数):");
fgets(s1, sizeof(s1), stdin);
s1[strcspn(s1, "\n")] = '\0';
printf("请输入第二个字符串(小写字符计数):");
fgets(s2, sizeof(s2), stdin);
s2[strcspn(s2, "\n")] = '\0';
int count1 = CountLowerCase(s1);
int count2 = CountLowerCase(s2);
printf("字符串s1中的小写字母个数为:%d\n", count1);
printf("字符串s2中的小写字母个数为:%d\n", count2);
return 0;
}
```
在这里,我们通过比较ASCII值范围的方式来判断字符是否在小写字母范围内。`*str >= 'a'` 和 `*str <= 'z'` 分别表示字符是小写字母的开始和结束位置。
阅读全文
相关推荐
















