21xrx.com
2024-06-02 23:01:18 Sunday
登录
文章检索 我的文章 写文章
C++实现单词最后出现行的统计
2023-06-27 17:27:33 深夜i     --     --
C++ 单词 最后出现行 统计

在文本处理过程中,有时候需要统计一个单词在文本中最后出现的行号。这种需求在程序员的日常工作中经常出现,特别是在代码调试和分析过程中。在C++中,可以使用一些字符串处理函数和文件读写操作实现单词最后出现行的统计。

下面是一个简单的实现示例:


#include <iostream>

#include <fstream>

#include <string>

using namespace std;

int main() {

  string word = "hello"; // 要统计的单词

  string filename = "example.txt"; // 文件名

  string line;

  int count = 0;

  int lastLine = 0; // 单词最后出现的行号

  ifstream file(filename); // 打开文件

  if (file.is_open()) { // 判断文件是否成功打开

    while (getline(file, line)) {

      count++; // 行号加一

      if (line.find(word) != string::npos) // 查找单词是否在这一行出现

        lastLine = count; // 记录下单词最后出现的行号

      

    }

    file.close(); // 关闭文件

  }

  else

    cout << "File open failed!" << endl;

  

  cout << "The last line of the word " << word << " in the file is: " << lastLine << endl;

  return 0;

}

在上面的示例中,首先定义了要统计的单词和文件名,然后使用ifstream打开文件,并逐行读取文件内容,查找单词是否在这一行出现,如果出现,则记录下行号。最后输出单词最后出现的行号。

需要注意的是,如果单词在文本中多次出现,此方法仅统计最后一次出现时的行号。

总的来说,通过上述简单的示例,我们可以看到如何使用C++实现单词最后出现行的统计功能,每个程序员都可以据此扩展实现更加复杂的文本处理操作。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复