考研真题C语言

【2015年山西大学考研真题】输入一行字符,分别统计其中英文字母、空格、数字和其他字符的

个数。


(1)算法的基本思想如下:

  1. 遍历输入的字符串,依次判断每个字符的类型。

  2. 判断字符的类型,根据字符的ASCII码范围来判断是否为英文字母、数字、空格或其他字符。

  3. 统计每种字符类型的个数。

(2)下面是使用C语言描述这个算法的代码:

```c

#include <stdio.h>

void countCharacters(char* str, int* letters, int* spaces, int* digits, int* others) {

char ch;

int i = 0;

while (str[i]) {

ch = str[i];

if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {

(*letters)++;

} else if (ch == ' ') {

(*spaces)++;

} else if (ch >= '0' && ch <= '9') {

(*digits)++;

} else {

(*others)++;

}

i++;

}

}

int main() {

char str[100];

int letters = 0, spaces = 0, digits = 0, others = 0;

printf("请输入一行字符:");

gets(str);

countCharacters(str, &letters, &spaces, &digits, &others);

printf("英文字母个数:%d\n", letters);

printf("空格个数:%d\n", spaces);

printf("数字个数:%d\n", digits);

printf("其他字符个数:%d\n", others);

return 0;

}

```

在上述代码中,我们定义了 `countCharacters` 函数来统计输入字符串中的每种字符类型的个数。在 `main` 函数中,我们读取输入字符串,并调用 `countCharacters` 来进行统计。

(3)算法的时间复杂度是 O(n),其中 n 是输入字符串的长度。我们需要遍历每个字符判断其类型,并累加对应的计数器。

相关推荐
聚客AI3 分钟前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
大怪v3 小时前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
惯导马工4 小时前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
骑自行车的码农6 小时前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了6 小时前
AcWing学习——双指针算法
c++·算法
moonlifesudo7 小时前
322:零钱兑换(三种方法)
算法
NAGNIP1 天前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队1 天前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja1 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法