簡體   English   中英

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

[英]Finding the most frequent character in a file in 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++)
    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;
}

現在函數返回最常出現的字母發生的次數,而不是字符本身。 我有點失落,因為我不確定這個功能應該是什么樣子。 它是否有意義,我怎么可能解決這個問題?

我將衷心感謝您的幫助。

可變frequency由字符代碼索引。 所以frequency[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 i = 1更改為int i = 0 從1開始意味着從B開始,這是一個你可能不會注意到的微妙錯誤。 此外,循環應終止於<= 26 ,否則你也會錯過Z

注意大括號。 您的大括號樣式(單語句塊沒有大括號) 非常不推薦。

此外,在這種情況下, i++++i更常見。 在這種情況下,它沒有任何區別,所以建議i++

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM