Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C中查找文件中最常用的字符_C - Fatal编程技术网

在C中查找文件中最常用的字符

在C中查找文件中最常用的字符,c,C,我正在编写一个函数,用于查找文件中最常见的字母字符。该函数应忽略除字母以外的所有字符 目前,我有以下几点: int most_common(const char *filename) { char frequency[26]; int ch = 0; FILE *fileHandle; if((fileHandle = fopen(filename, "r")) == NULL){ return -1; } for (ch = 0; ch < 26; ch++) fre

我正在编写一个函数,用于查找文件中最常见的字母字符。该函数应忽略除字母以外的所有字符

目前,我有以下几点:

int most_common(const char *filename)
{
char frequency[26];
int ch = 0;

FILE *fileHandle;
if((fileHandle = fopen(filename, "r")) == NULL){
    return -1;
}

for (ch = 0; ch < 26; ch++)
    frequency[ch] = 0;

while(1){
    ch = fgetc(fileHandle);
    if (ch == EOF) break;

    if ('a' <= ch && ch  <= 'z')
        frequency[ch - 'a']++;
    else if ('A' <= ch && ch <= 'Z')
        frequency[ch - 'A']++;
}

int max = 0;
for (int i = 1; i < 26; ++i)
  if (frequency[i] > frequency[max])
      max = i;

return max;
}
int最常见(常量字符*文件名)
{
字符频率[26];
int ch=0;
文件*文件句柄;
if((fileHandle=fopen(filename,“r”))==NULL){
返回-1;
}
对于(ch=0;ch<26;ch++)
频率[ch]=0;
而(1){
ch=fgetc(文件句柄);
如果(ch==EOF)中断;

如果('a'变量
频率
由字符代码索引。因此
频率[0]
为5,如果有5个'a'

在代码中,您将计数分配给
max
,而不是字符代码,因此您返回的是计数而不是实际字符

您需要存储最大频率计数及其引用的字符代码

我会用以下方法解决这个问题:

int maxCount = 0;
int maxChar = 0;
// i = A to Z
for (int i = 0; i <= 26; ++i)
{
  // if freq of this char is greater than the previous max freq
  if (frequency[i] > maxCount)
  {
      // store the value of the max freq
      maxCount = frequency[i];

      // store the char that had the max freq
      maxChar = i;
  }
}

// character codes are zero-based alphabet.
// Add ASCII value of 'A' to turn back into a char code.
return maxChar + 'A';
int maxCount=0;
int maxChar=0;
//i=A到Z
对于(int i=0;i maxCount)
{
//存储最大频率的值
最大计数=频率[i];
//存储具有最大频率的字符
maxChar=i;
}
}
//字符代码是以零为基础的字母表。
//将ASCII值“A”添加回字符代码。
返回maxChar+'A';

请注意,我将
int I=1
更改为
int I=0
。从1开始意味着从
B开始,这是一个您可能没有注意到的细微错误。此外,循环应该在
处终止。您的程序看起来不错。您的问题到底是什么?如果要返回最频繁的字符,您只需更改最后一个行,以便在注册
max
的同时跟踪它。我还建议避免对没有花括号的/if
语句使用
。这是邪恶且容易出错的。Joe的答案是好的。我只想补充一点,最好将
字符频率[26]
更改为
int-frequency[26]
。甚至
long
。否则,如果输入文本包含的相同字母超过255个(例如,270
A
s),代码将无法正常工作,因为计数器将溢出。除了A-Z和A-Z之外,还有很多字母字符。如果您的算法不打算处理它们,只需异常终止,例如,
If(ch>127)return-2;
。非常感谢!现在它可以正常工作,直到使用空文件测试函数为止。它不会返回0,而是返回“A”。不知何故,您需要找到一种方法从函数中返回没有max字符的信息。一种方法是返回一个特殊的数字,如
-1
,以表明这一点。我不会编写为您编写代码!为什么不考虑将
maxChar
设置为一个特殊的初始值,这样如果它从未更改过,您就可以知道。或者在循环中设置一个布尔标志,以便知道它是否运行过。