Are you searching for how to find the first repeated word in a string? Use the below c++ program to find the first repeated word in a string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | #include <bits/stdc++.h> using namespace std; string findFirstRepeated(string s) { istringstream iss(s); string token; unordered_map<string, int> setOfWords; while (getline(iss, token, ' ')) { if (setOfWords.find(token) != setOfWords.end()) setOfWords[token] += 1; // word exists else // insert new word to set setOfWords.insert(make_pair(token, 1)); } // either take a new stream or store the words // in vector of strings in previous loop istringstream iss2(s); while (getline(iss2, token, ' ')) { int count = setOfWords[token]; if (count > 1) { return token; } } return "NoRepetition"; } int main() { string s("Prem had been saying that he had been there"); string firstWord = findFirstRepeated(s); if (firstWord != "NoRepetition") cout << "First repeated word: " << firstWord << endl; else cout << "No Repetitionn"; return 0; } |
Program Output
1 | First repeated word: had |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.