Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Remove Duplicate/Repeated words from String

  • Difficulty Level : Easy
  • Last Updated : 25 Oct, 2021

Java


Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.



import java.io.*;
 
class GFG {
  public static void main(String[] args) {
         
        System.out.println("Enter The String : ");
        String str = "geeksforgeeks";
        StringBuffer sb = new StringBuffer();
        str.chars().distinct().forEach(c -> sb.append((char) c));
        String DuplicateString = sb.toString();
        System.out.println("String after duplicates removed :"+DuplicateString);
    }
}

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 
Explanation: here ‘Geeks’ and ‘for’ are duplicate so these words are removed from the 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: here ‘your’ is the duplicate word so that word is removed from 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++.
 

CPP




// 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;
}
Output: 
Geeks for A Computer Science portal

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :