How to find words around a specific word in a file

I have a large file in my results. I want to search for words around a specific word in this file. For example, if I have a file like this: I am going to go home. They are going to school. Sam is going to lunch.

How can I get the words before and after the "transition" and store them in a hash using C ++.

0
source share
1 answer

You can simply read the file word by word, always keeping N words as context. You can save the context in std::deque, which allows the sliding 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();
}
+2
source

Source: https://habr.com/ru/post/1621156/


All Articles