优化这段代码
时间: 2023-08-11 19:16:50 浏览: 40
可以使用fgets函数一次性读取一行字符串,并对其进行处理,避免了使用getchar函数逐个读取字符的时间开销。可以将代码优化为如下形式:
```c
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX_LEN 1000
int main() {
int english = 0, digit = 0, space = 0, other = 0;
char str[MAX_LEN];
fgets(str, MAX_LEN, stdin);
int len = strlen(str);
for (int i = 0; i < len; i++) {
char c = str[i];
if (isalpha(c)) {
english++;
} else if (isdigit(c)) {
digit++;
} else if (isspace(c)) {
space++;
} else {
other++;
}
}
printf("%d %d %d %d", english, digit, space, other);
return 0;
}
```
这里我们定义了一个MAX_LEN常量来限制输入字符串的最大长度,使用fgets函数一次性读取一行字符串,并将其存储在字符数组str中。然后使用strlen函数获取输入字符串的长度,使用for循环逐个遍历字符串中的所有字符,判断其类型并更新相应计数器。最后输出统计结果。
这个代码优化后,避免了使用getchar函数逐个读取字符的时间开销,可以更快地执行完成,避免了超时的问题。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.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_lunwen.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)