Find the first repeated word in a string | CPP program for finding first repeated word in a string ; returns first repeated word ; break string into tokens and then each string into set if a word appeared before appears again , return the word and break ; hashset for storing word and its count in sentence ; store all the words of string and the count of word in hashset ; if word exists return ; insert new word to set ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; string findFirstRepeated ( string s ) { istringstream iss ( s ) ; string token ; set < string > setOfWords ; while ( getline ( iss , token , ' ▁ ' ) ) { if ( setOfWords . find ( token ) != setOfWords . end ( ) ) { return token ; } setOfWords . insert ( token ) ; } return " NoRepetition " ; } int main ( ) { string s ( " Ravi ▁ 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 ; }