Print all unique words of a String - GeeksforGeeks

27 Jan, 2022
Write a function that takes a String as an argument and prints all unique words in it.
Examples:
Input : Java is great. Grails is also great
Output : Java
         Grails
         also
Approach:The idea is to use map to keep track of words already occurred. But first, we have to extract all words from a String, as a string may contain many sentences with punctuation marks.For extracting words from a String, refer Extracting each word from a String.
Python: The idea is to use a Dictionary for calculating the count of each word. But first, we have to extract all words from a String because a string may contain punctuation marks. This is done using regex or regular expression. The word which has count 1 in the dictionary is a unique word.
Java
Python3
// Java program to print unique words// from a string import java.util.HashMap;import java.util.Iterator;import java.util.Set;import java.util.regex.Matcher;import java.util.regex.Pattern; public class Test{    // Prints unique words in a string    static void printUniquedWords(String str)    {        // Extracting words from string        Pattern p = Pattern.compile("[a-zA-Z]+");        Matcher m = p.matcher(str);                 // Map to store count of a word        HashMap<String, Integer> hm = new HashMap<>();                 // if a word found        while (m.find())        {            String word = m.group();                         // If this is first occurrence of word            if(!hm.containsKey(word))                hm.put(word, 1);            else                // increment counter of word                hm.put(word, hm.get(word) + 1);                     }                 // Traverse map and print all words whose count        // is  1        Set<String> s = hm.keySet();        Iterator<String> itr = s.iterator();         while(itr.hasNext())        {            String w = itr.next();                         if (hm.get(w) == 1)                System.out.println(w);        }       }         // Driver Method    public static void main(String[] args)    {        String str = "Java is great. Grails is also great";        printUniquedWords(str);    }}
# Python program to print unique word# in a string.# Using re (Regular Expression module)# It is used here to match a pattern# in the given stringimport re # Declare a dictionarydict = {} # Method to check whether the word# exists in dictionary or notdef uniqueWord(Word):     if Word in dict:         # If the word exists in dictionary then        # simply increase its count        dict[words] += 1     else:         # If the word does not exists in        # dictionary update the dictionary        # and make its count 1        dict.update({words: 1}) # Driver codeif __name__ == '__main__':         string = "Java is great. Grails is also great"         # re.split() method is used to split    # all the words in a string separated    # by non-alphanumeric characters (\W)    ListOfWords = re.split("[\W]+", string)     # Extract each word from ListOfWords    # and pass it to the method uniqueWord()    for words in ListOfWords:        uniqueWord(words)     # Iterate over dictionary if the value    # of the key is 1, then print the element    for elements in dict:        if dict[elements] == 1:            print(elements)
Java
Grails
also
This article is contributed by Gaurav Ahirwar and Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
Method 2:using set()
Approach:
In this approach, we store the string in the form of a set of individual words and print the words. To solve this problem in this method, first we need to know about https://www.geeksforgeeks.org/sets-in-python/
Below is the implementation of the above approach:
Python3
# python program to print all# the unique words in a string# in python using set() method# function to print unique words  def printWords(l):         # for loop for iterating    for i in l:        print(i)  # Driver codestr = "geeks for geeks" # storing string in the form of list of wordss = set(str.split(" ")) # passing list to print words functionprintWords(s)
geeks
for
Ronit_shrivastava
skate1512
vikkycirus
gabaa406
amartyaghoshgfg
Java-String-Programs
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in Java
Stream In Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Internal Working of HashMap in Java
Checked vs Unchecked Exceptions in Java
Strings in Java
StringBuilder Class in Java with Examples