考研真题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 (stri) {

ch = stri;

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 str100;

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

相关推荐
罗西的思考3 小时前
【Agentic RL / 强化学习框架】Molt 设计解读
人工智能·算法·机器学习
hahaha60164 小时前
HLS高层次综合设计技巧--C++类和模板
图像处理·人工智能·算法·计算机视觉
多弗朗皮卡丘4 小时前
算法详解4:买卖股票的最佳时机系列(上)
算法
Brilliantwxx6 小时前
【C语言】 初入嵌入式C语言复习(基础+进阶面试题)
c语言·开发语言
wuminyu7 小时前
深入剖析 Panama Off-heap 的性能损耗与开销
java·linux·c语言·jvm·c++
维克兜率天7 小时前
【维克】动量指标家族:RSI、ROC、CCI、Momentum全面解析
python·算法
rhythm-ring7 小时前
宏定义续行符 \ 的使用与踩坑
c语言·c++
AI情绪识别开源7 小时前
检信 AI 智能推广平台(代号:JX-Promote)
人工智能·算法·erlang
老当益壮梁奶奶8 小时前
Linux软件编程学习笔记(八):进程间通信详解(1)
linux·c语言·笔记·学习·算法
「QT(C++)开发工程师」8 小时前
C++11 std::unique_ptr — 独占所有权的智能指针
c语言·开发语言·c++·qt