

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the first repeated word in a string in C++
In this problem, we are a string str consisting of comma separated words. Our task is to find the first repeated word in a string.
We need to find the first word 'string between two spaces' which gets repeated in the string.
Let's take an example to understand the problem,
Input : str = "C program are easy to program" Output : program
Solution Approach
A simple solution to the problem is using hashmap data structure. To find the first repeated word, we will store each word and its count (number of times it appeared in the string ) in the hashmap. For this we will keep checking if the current word is present or not.
Then we will print the first work with more than one occurrence count in the hashmap.
Example
Program to illustrate the working of our solution
#include <bits/stdc++.h> using namespace std; string findFirstRepeatWord(string str){ istringstream iss(str); string word; unordered_map<string, int> wordCountMap; while (getline(iss, word, ' ')) { if (wordCountMap.find(word) != wordCountMap.end()) wordCountMap[word] ++; else wordCountMap.insert(make_pair(word, 1)); } istringstream iss2(str); while (getline(iss2, word, ' ')) { int count = wordCountMap[word]; if (count > 1) { return word; } } return "NoRepetition"; } int main(){ string str = "C program are easy to program"; string repeatedWord = findFirstRepeatWord(str); if (repeatedWord != "NoRepetition") cout<<"The first repeated word is '"<<repeatedWord<<"'"; else cout<<"No word is Repeated in the string"; return 0; }
Output
The first repeated word is 'program'
This program uses a lot of in-build functions for making the task easier.
- Related Questions & Answers
- Find the first repeated word in a string in Python?
- Find the first repeated word in a string in Java
- Find the first repeated word in a string in Python using Dictionary
- Find the first repeated character in a string using C++.
- Find repeated character present first in a string in C++
- Find the second most repeated word in a sequence in Java
- Find the first maximum length even word from a string in C++
- How to replace only the first repeated value in a string in MySQL
- PHP program to find the first word of a sentence
- Second most repeated word in a sequence in Python?
- Print first letter of each word in a string in C#
- Get distinct first word from a string with MongoDB?
- Python - Find the length of the last word in a string
- Java Program to Capitalize the first character of each word in a String
- How to print the first character of each word in a String in Java?
Advertisements