问题描述:要求编程建立一个文本文件,每个单词不包含空格且不跨行,单 词由字符序列构成且区分大小写。 要求: 1、统计给定单词在文本文件中出现的总次数; 2、检索输出某个单词出现在文本中的行号、在该行中出现的次数以及位 置。用C++
时间: 2024-02-25 07:59:08 浏览: 22
好的,以下是可以实现你的要求的C++代码:
```c++
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
string filename, word;
cout << "请输入文件名:";
cin >> filename;
cout << "请输入要查询的单词:";
cin >> word;
ifstream file(filename);
if (!file) {
cout << "无法打开文件!" << endl;
return 1;
}
vector<string> lines;
string line;
while (getline(file, line)) {
lines.push_back(line);
}
vector<vector<int>> pos(lines.size());
int count = 0;
for (int i = 0; i < lines.size(); i++) {
string::size_type index = 0;
while ((index = lines[i].find(word, index)) != string::npos) {
pos[i].push_back(index);
count++;
index += word.size();
}
}
cout << "单词总出现次数:" << count << endl;
for (int i = 0; i < pos.size(); i++) {
if (!pos[i].empty()) {
cout << "第" << i+1 << "行出现次数:" << pos[i].size() << ",位置分别为:";
for (int j = 0; j < pos[i].size(); j++) {
cout << pos[i][j] << " ";
}
cout << endl;
}
}
return 0;
}
```
这段代码首先让用户输入文件名和要查询的单词,然后打开文件并逐行读取文本内容,将每行字符串保存到一个vector中。接着对于每行字符串,使用find函数查找单词出现的位置,并将这些位置保存到一个二维vector中。最后输出单词总出现次数和每行出现次数以及位置。
需要注意的是,由于文件中的单词可能会有大小写不同的情况,因此需要使用find函数的第三个参数指定搜索的起始位置,以便找到所有出现位置。另外,由于文本中可能会有多个单词出现在同一位置,因此需要将位置保存在一个vector中。