21xrx.com
2025-04-14 11:59:55 Monday
文章检索 我的文章 写文章
C++实现英文单词个数计算
2023-07-13 20:25:42 深夜i     9     0
C++ 实现 英文单词 个数计算

在编程语言中,C++是一种功能强大的对象导向编程语言。它是一个通用的编程语言,广泛应用于各种编程领域中。在这个编程语言中,我们可以实现许多有用的功能,如英文单词个数计算程序。

在计算机编程中,英文单词个数计算程序是一种非常常见的应用。这种程序能够从一段英文文本中提取出所有的单词,并且计算出这段文本中单词的个数。

要实现这样的程序,我们需要先了解一些基本的编程知识。我们需要知道如何读入文本数据,并将它们处理成单词。我们还需要用到一些字符串处理函数,如split()和find(),以帮助我们提取出单词。最后,我们需要利用标准模板库中的容器,如vector和map,以便在内存中存储和修改数据。

在下面的代码示例中,我们将展示如何使用C++实现英文单词个数计算程序。我们将通过以下步骤来完成程序:

首先,我们需要引入一些必要的头文件,如iostream、string、vector和map。

接下来,我们定义一个split()函数,以将文本数据拆分成单词。该函数从文本输入中读取数据,并将单词存储在一个字符串向量中。

然后,我们定义一个remove_punctuation()函数,以去除每个单词中的标点符号。该函数从输入中读取一个单词,并将其返回,但是不包含标点符号。

接下来,我们定义一个count_words()函数,以计算文本中单词的个数。该函数使用map容器来存储单词并计算它们的出现次数。

最后,我们在主程序中调用上述函数,并输出计算结果。

#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;
vector<string> split(string str, char delimiter) {
  vector<string> words;
  string word = "";
  for (auto s : str) {
   if (s == delimiter) {
     words.push_back(word);
     word = "";
   } else {
     word += s;
   }
  }
  words.push_back(word);
  return words;
}
string remove_punctuation(string word) {
  string new_word;
  for (auto s : word) {
    if ((s >= 'a' && s <= 'z') || (s >= 'A' && s <= 'Z')) {
      new_word += s;
    }
  }
  return new_word;
}
void count_words(string str) {
  map<string, int> word_count;
  vector<string> words = split(str, ' ');
  for (auto word : words) {
   word = remove_punctuation(word);
   if (word.empty())
     continue;
   
   word_count[word]++;
  }
  for (auto p : word_count)
   cout << p.first << ": " << p.second << endl;
 
}
int main() {
  string text = "This is a test text. Do you know how many words are in it? ";
  cout << "Number of words in text: " << endl;
  count_words(text);
  return 0;
}

在上面的代码中,我们从文本“这是一个测试文本。你知道里面有多少个单词吗?”中读取了一段英文输入,并使用我们定义的函数计算出文本中的单词个数。输出结果为:

Number of words in text:
Do: 1
This: 1
a: 1
are: 1
how: 1
in: 1
is: 1
it: 1
know: 1
many: 1
text: 1
test: 1
you: 1

在这个例子中,我们看到了C++中构建英文单词计数程序的基本方法。我们通过定义和使用各种字符串处理函数和容器来完成这项任务。这项任务的优点在于它具有广泛的适用性,并且可以轻松扩展以处理更大、更复杂的文本数据。

  
  

评论区

    相似文章
请求出错了