user2162685
user2162685

Reputation:

How to find words around a particular word in a file

I have a big file in my results. I want to look for words around a specific word in this file. For example, if I have a file like this: I am going home they are going school sam is going to lunch

How can I get words before and after "going" and save it in a hash using C++.

Upvotes: 0

Views: 379

Answers (1)

Olaf Dietsche
Olaf Dietsche

Reputation: 74018

You can just read the file word by word, always keeping N words as context. You can store the context in a std::deque which allows a rolling context

const int N = 10;
std::deque<std::string> words_before, words_after;
std::string current_word, w;

// prefetch words before and after
for (int i = 0; i < N; ++i) {
    std::cin >> w;
    words_before.push_back(w);
}

std::cin >> current_word;

for (int i = 0; i < N - 1; ++i) {
    std::cin >> w;
    words_after.push_back(w);
}

// now process the words and keep reading
while (std::cin >> w) {
    words_after.push_back(w);
    // save current_word with the words around words_before, words_after
    words_before.pop_front();
    words_before.push_back(current_word);
    current_word = words_after.front();
    words_after.pop_front();
}

Upvotes: 2

Related Questions