编一程序,它读入一行正文,统计在正文中出现的各个字的次数,并按照字典顺序显示结果。
时间: 2024-03-25 20:39:02 浏览: 9
好的,以下是 Python 语言的实现示例:
```python
text = input("请输入一行正文:")
count = {}
# 统计每个字的出现次数
for char in text:
if char.isalpha(): # 只考虑字母
if char not in count:
count[char] = 1
else:
count[char] += 1
# 按照字典顺序排序并输出结果
for char in sorted(count.keys()):
print(char, ":", count[char])
```
以上程序会先读入一行正文,然后利用字典统计每个字的出现次数,最后按照字典顺序排序并输出结果。注意,这里只考虑字母,忽略其他字符。
相关问题
用C语言编一程序,它读入一行正文,统计在正文中出现的各个字的次数,并按照字典顺序显示结果。
好的,以下是 C 语言的实现示例:
```c
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX_LEN 1000 // 假设输入不超过 1000 个字符
int main() {
char text[MAX_LEN];
int count[26] = {0}; // 26 个字母的出现次数
// 读入一行正文
printf("请输入一行正文:");
fgets(text, MAX_LEN, stdin);
// 统计每个字母的出现次数
int len = strlen(text);
for (int i = 0; i < len; i++) {
char c = tolower(text[i]); // 转换为小写字母
if (isalpha(c)) {
count[c - 'a']++;
}
}
// 按照字典顺序输出结果
for (int i = 0; i < 26; i++) {
if (count[i] > 0) {
printf("%c : %d\n", 'a' + i, count[i]);
}
}
return 0;
}
```
以上程序会先读入一行正文,然后利用数组统计每个字母的出现次数,最后按照字典顺序输出结果。注意,这里区分大小写,但是输出时都转换为小写字母。
用C语言编一程序,它读入一行正文,统计在正文中出现的各个字的次数,并按照字典顺序显示结果。 例如,如果输入的正文为:how do you do?
好的,以下是用C语言编写的程序,可以实现读入一行正文,统计在正文中出现的各个字的次数,并按照字典顺序显示结果:
```c
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX_WORD_LEN 100
struct word {
char str[MAX_WORD_LEN];
int count;
};
int main() {
char line[MAX_WORD_LEN];
int len, i, j, k, count;
struct word words[MAX_WORD_LEN / 2];
printf("请输入一行正文:\n");
fgets(line, MAX_WORD_LEN, stdin);
len = strlen(line);
// 统计每个单词出现的次数
count = 0;
for (i = 0; i < len; i++) {
// 跳过非字母字符
if (!isalpha(line[i])) {
continue;
}
// 找到单词的结束位置
j = i;
while (j < len && isalpha(line[j])) {
j++;
}
// 将单词存入数组中
for (k = 0; k < count; k++) {
if (strncmp(words[k].str, line + i, j - i) == 0) {
words[k].count++;
break;
}
}
if (k == count) {
strncpy(words[k].str, line + i, j - i);
words[k].count = 1;
count++;
}
i = j;
}
// 按照字典顺序排序
for (i = 0; i < count - 1; i++) {
for (j = i + 1; j < count; j++) {
if (strcmp(words[i].str, words[j].str) > 0) {
struct word temp = words[i];
words[i] = words[j];
words[j] = temp;
}
}
}
// 输出结果
printf("各个字出现的次数如下:\n");
for (i = 0; i < count; i++) {
printf("%s:%d\n", words[i].str, words[i].count);
}
return 0;
}
```
你可以将以上代码复制到一个文本编辑器中,保存为一个以 `.c` 为扩展名的文件,然后在命令行中使用 C 编译器进行编译。例如,在 Windows 下,你可以使用以下命令进行编译:
```
gcc word_count.c -o word_count
```
编译完成后,你可以在命令行中输入 `word_count` 来运行程序,按照提示输入一行正文,程序将会输出每个字出现的次数。