c - 如何获得单词中出现频率最高的字母?
问题描述
我正在尝试获取字符串中最常见的字母,其中只有大写字母,单词之间没有空格。为此,我使用了一个函数,该函数maxArray(array, sizeof array)
给出数组中的最大数字,以计算字母重复的次数,并将信息存储在另一个数组中字符串中每个字母的相同位置。但是在我提出的两种算法中它不起作用。
PS:我只是一个初学者。
这是代码:
int maxArray(int *tab, int n) {
int i, tmp;
tmp = tab[0];
for (i = 1; i < n; i++) {
if (tmp < tab[i])
tmp = tab[i];
}
return tmp;
}
//first algo(didn't finish it)
char occurencedelettre(char *string) {
int *array;
int i, j, compt, max;
for (i = 0; string[i] !='\0'; i++) {
compt = 0;
for (j = 0; string[j] !='\0'; j++) {
if (string[i] == string[j])
compt++;
}
array[i] = compt;
}
return array;
}
//second one
char occurencedelettre(char *string) {
int count[25] = { 0 };
int x = 0;
char result;
for (int i = 0; string[i] != '\0'; i++) {
count[string[i]]++;
if (x < count[string[i]]) {
x = count[string[i]];
result = string[i];
}
}
return result;
}
解决方案
第二种方法几乎是正确的,除了这些问题:
- 数组的长度应为 26
- 您必须
'A'
从字母的值中减去 和 之间的索引0
,25
假设该单词仅包含 ASCII 中的大写字母。 - 您必须初始化
result
以返回0
(或任何其他特定值)空字。
这是修改后的版本:
char occurencedelettre(const char *string) {
size_t count[26] = { 0 };
size_t x = 0;
char result = '\0';
for (size_t i = 0; string[i] != '\0'; i++) {
count[string[i] - 'A']++;
if (x < count[string[i]]) {
x = count[string[i]];
result = string[i];
}
}
return result;
}
第一种方法更麻烦、更慢,但也更通用,因为它可能适用于任何单词内容。这是修改后的版本:
char occurencedelettre(const char *string) {
char result = 0;
size_t max_count = 0;
for (size_t i = 0; string[i] != '\0'; i++) {
size_t count = 1;
for (size_t j = i + 1; string[j] != '\0'; j++) {
if (string[i] == string[j])
count++;
}
if (max_count < count) {
max_count = count;
result = string[i];
}
}
return result;
}
请注意,您可以针对任何字内容调整第一种方法,假设为 8 位字节:
char occurencedelettre(const char *string) {
size_t count[256] = { 0 };
size_t x = 0;
char result = '\0';
for (size_t i = 0; string[i] != '\0'; i++) {
count[(unsigned char)string[i]]++;
if (x < count[(unsigned char)string[i]]) {
x = count[(unsigned char)string[i]];
result = string[i];
}
}
return result;
}
推荐阅读
- javascript - 关于:在excel中导出表格时出现空白#blocked错误
- oracle - 在 oracle apex 中更改错误系统消息
- python - 如何记录电子邮件的内容以便不再发送重复的电子邮件?
- mysql - 通过比较可空列连接三个表
- c# - 如何根据另一个选择下拉jquery MVC过滤一个选择?
- android - 关于操作栏、工具栏和菜单图标的问题
- javascript - 将 FileList 发送到 Flask 后端?
- asp.net-mvc - 在主视图上调用带有表格的 Partialview
- scala - 我有一个这样的数据框如何使用 spark scala 删除这些特殊字符?
- c# - 从字典列表中提取记录,其中键和值不包含给定值列表c#