在C中,我需要创建一个函数,对于输入,它将计算并显示每个字母出现的次数.
对于"Lorem ipsum dolor sit amet"的输入,该函数应返回类似于:
a: 0
b: 0
c: 0
d: 1
e: 2
f: 0
...
Run Code Online (Sandbox Code Playgroud)
因此,您基本上需要读取整个文件char-by-char.假设你知道文件阅读是如何工作的,你需要做一些事情(道歉,自从我做了C之后已经有一段时间了):
if (isalpha(ch)) {
count[ch-'a']++;
}
/* rest of code where char pointer is moved on etc. */
Run Code Online (Sandbox Code Playgroud)
您需要为此导入ctype库:
#include <ctype.h>
Run Code Online (Sandbox Code Playgroud)
**忘了提,假设你会推断出以下内容:ch是你指向当前读入字符的指针,而count []是一个int [],初始化为所有零,大小为(26*2)= 52到适合大小写.如果大写和小写应该相同,则可以使用ctype库中也包含的tolower(int c)函数.在这种情况下,您只需要一个26大小的数组.
if (isalpha(ch)) {
count[tolower(ch)-'a']++;
}
Run Code Online (Sandbox Code Playgroud)
然后count []应包含每个字符的计数.
/*******/
如果只想用stdio.h库执行此操作,则可以实现ctype.h库中使用的两个函数.
isalpha(int c)函数的简单实现可能是这样的:
if (((int)c >= 'a' && (int)c <= 'z') || ((int)c >= 'A' && (int)c <= 'Z') {
return TRUE;
} else {
return FALSE;
}
Run Code Online (Sandbox Code Playgroud)
(其中TRUE和FALSE属于您的返回类型和您定义的类型).
一个真正简单的tolower版本可能是这样的:
if ((int)c >= 'A' && (int)c <= 'Z') {
return (int)c - 'a';
} else {
return (int)c;
}
Run Code Online (Sandbox Code Playgroud)
你可能没有所有演员......