Remove Duplicate/Repeated words from String

Given a string, we have to remove all duplicate/repeated words from the string.

Examples:

Input: str = “Geeks for Geeks A Computer Science portal for Geeks”
Output: Geeks for A Computer Science portal geeks
Explanation: here ‘Geeks’ and ‘for’ are duplicate so these words are removed from string
 
Input: “Publish your own articles on GeeksforGeeks and share your knowledge with the world”
Output: Publish your own articles on GeeksforGeeks and share knowledge with the world
Explanation: No any repeated word in this string



We create an empty hash table. Then split given string around spaces. For every word, we first check if it is in hash table or not. If not found in hash table, we print it and store in the hash table.

To split given string into words, we use stringstream in C++.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to remove duplicate
// word from string
#include <bits/stdc++.h>
using namespace std;
  
void removeDupWord(string str)
{
    // Used to split string around spaces.
    istringstream ss(str);
  
    // To store individual visited words
    unordered_set<string> hsh;
  
    // Traverse through all words
    do
    {
        string word;
        ss >> word;
  
        // If current word is not seen before.
        while (hsh.find(word) == hsh.end()) {
            cout << word << " ";
            hsh.insert(word);
        }
  
    } while (ss);
}
  
// Driver function
int main()
{
    string str = "Geeks for Geeks A Computer"
                " Science portal for Geeks";
    removeDupWord(str);
    return 0;
}

chevron_right


Output:

Geeks for A Computer Science portal


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.