考研真题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 是输入字符串的长度。我们需要遍历每个字符判断其类型,并累加对应的计数器。

相关推荐
康谋自动驾驶2 小时前
拆解3D Gaussian Splatting:原理框架、实战 demo 与自驾仿真落地探索!
算法·数学建模·3d·自动驾驶·汽车
一念&2 小时前
每日一个C语言知识:C 共用体
c语言
violet-lz3 小时前
数据结构八大排序:希尔排序-原理解析+C语言实现+优化+面试题
数据结构·算法·排序算法
ezl1fe3 小时前
第一篇:把任意 HTTP API 一键变成 Agent 工具
人工智能·后端·算法
冯诺依曼的锦鲤3 小时前
算法练习:双指针专题
c++·算法
吃着火锅x唱着歌3 小时前
LeetCode 668.乘法表中第k小的数
算法·leetcode·职场和发展
前端小刘哥3 小时前
互联网直播点播平台EasyDSS流媒体技术如何赋能多媒体展厅智能化升级?
算法
Python算法实战3 小时前
平安大模型面试题:Self-Attention 原理与多头注意力设计
人工智能·算法·自然语言处理·大模型·面试题
Python算法实战4 小时前
腾讯送命题:手写多头注意力机制。。。
人工智能·算法·面试·大模型·强化学习