Find the first repeated word in string in C++

Find first repeated word in string

Today in this article we will be discussing how to find the First repeated word in string.

Lets understand this with the help of example :- 

  • Input:- “Launch an app that runs faster and faster than other app okay”
  • Output:- app

here as you can in the string the word app is the first repeated word.

First repeated word in string

Algorithm

  • In the main code we have taken firstWord and stored the value of  findFirstRepeated(s) and in the function we will return the word that is stored in the token that is the first repeated string.
  • And if there is no first repeated word then it will return the empty string and then in the main code we will check and print accordingly.
  • Here we take a hashmap unordered_map  word_with_count  that has a word and its count.
  • Then we iterate the string and for each word of that string we increase the count if the string is already present else we create a new entry.
  • Then we will traverse the hashmap and get the word whose count is more than 1

Note:- The istringstream is a string class object which is used to stream the string into different variables and similarly files can be streamed into strings.

Find The first Repeated Word in String

C++ Code :-

string findFirstRepeated(string s) {

   istringstream iss(s);
   string token;
   unordered_map<string, int> word_with_count;
   while (getline(iss, token, ' ')) {
       if (word_with_count.find(token) != word_with_count.end()) {
           // old word, increase count
           word_with_count[token] += 1;
       } else {
           // as it is a new word, insert it
           word_with_count.insert(make_pair(token, 1));
       }
   }
   istringstream iss2(s);
   while (getline(iss2, token, ' ')) {
       // now check if the word exist and the count is greater than 1
       int count = word_with_count[token];
       if (count > 1) {
           return token;
       }
   }
   return " ";
}
// driver code
int main() {
   string s("Launch an app that runs faster and faster than other app okay");
   string firstWord = findFirstRepeated(s);
   if(firstWord != " ")
       cout << "The first repeated word is = " << firstWord << endl;
   else
       cout << "No Repetition found";
   return 0;
}

Output:-

 The first repeated word is = app