21xrx.com
2025-04-10 22:10:34 Thursday
文章检索 我的文章 写文章
C++实现单词出现次数统计
2023-07-05 04:50:27 深夜i     --     --
C++ 单词 出现次数 统计

C++是一种非常流行的编程语言,它已经被广泛用于编写各种应用程序。在本文中,我们将探讨C++如何实现单词出现次数统计。

在C++中,实现单词出现次数统计主要涉及以下几个步骤:

1. 读取文本文件

首先,我们需要读取包含待处理文本的文件。可以通过输入输出流来实现,即使用ifstream类来打开文件并读取其中的内容。

2. 分离单词

接下来,我们需要将文本划分为单词。这可以通过使用字符串处理函数来实现。具体来说,我们可以使用strtok()函数将文本拆分为一个个单词,然后将这些单词存储到字符串数组中。

3. 统计单词出现次数

一旦我们拥有了单词数组,就可以开始统计单词出现次数了。我们可以使用循环来遍历数组中的所有单词,并在每次循环中检查当前单词是否已经出现。如果已经出现过,则将该单词的出现次数加1。否则,我们将该单词添加到一个名称数组中,并将其出现次数初始化为1。

4. 输出结果

最后,我们需要将结果输出到屏幕或文本文件中。这可以通过使用cout或fprintf函数来实现。在输出结果时,我们可以使用循环来遍历所有单词和它们的出现次数,并将它们打印出来。

附代码如下:

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
const int MAX_WORDS = 1000;
const int MAX_WORD_LEN = 50;
int main() {
  char filename[100];
  char line[MAX_WORD_LEN];
  char *words[MAX_WORDS];
  int counts[MAX_WORDS] = {0};
  int num_words = 0;
  cout << "Enter the file name: " << endl;
  cin >> filename;
  ifstream file(filename);
  if (!file)
    cout << "File not found!" << endl;
    return 1;
  
  while (!file.eof()) {
    file >> line;
    char *word = strtok(line, " ,.?!:;");
    while (word != nullptr) {
      bool found = false;
      for (int i = 0; i < num_words; i++) {
        if (strcmp(words[i], word) == 0) {
          counts[i]++;
          found = true;
          break;
        }
      }
      if (!found) {
        words[num_words] = new char[strlen(word) + 1];
        strcpy(words[num_words], word);
        counts[num_words]++;
        num_words++;
      }
      word = strtok(nullptr, " ,.?!:;");
    }
  }
  for (int i = 0; i < num_words; i++) {
    cout << words[i] << " appears " << counts[i] << " times." << endl;
  }
  for (int i = 0; i < num_words; i++) {
    delete[] words[i];
  }
  file.close();
  return 0;
}

以上就是C++实现单词出现次数统计的方法和过程。该方法可以应用于文本处理、自然语言处理等多个领域。

  
  

评论区