Open In App

Print all unique words of a String

Improve
Improve
Like Article
Like
Save
Share
Report

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.

C++
#include <iostream>
#include <unordered_map>
#include <regex>

using namespace std;

// Function to print unique words in a string
void printUniqueWords(string str)
{
    // Extracting words from string
    regex pattern("[a-zA-Z]+");
    smatch match;

    // Map to store count of a word
    unordered_map<string, int> wordCount;

    // Iterating over words in the string
    while (regex_search(str, match, pattern))
    {
        string word = match.str();

        // If this is the first occurrence of the word
        if (wordCount.find(word) == wordCount.end())
            wordCount[word] = 1;
        else
            // Increment counter of the word
            wordCount[word] += 1;

        // Move to the next match
        str = match.suffix();
    }

    // Traverse map and print all words whose count is 1
    for (auto const &pair : wordCount)
    {
        if (pair.second == 1)
            cout << pair.first << endl;
    }
}

// Driver Method
int main()
{
    string str = "Java is great. Grails is also great";
    printUniqueWords(str);
    return 0;
}
Java
// 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);
    }
}
C#
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

class MainClass {
    // Function to print unique words in a string
    static void PrintUniqueWords(string str)
    {
        // Extracting words from string
        Regex pattern = new Regex("[a-zA-Z]+");
        MatchCollection matches = pattern.Matches(str);

        // Dictionary to store count of a word
        Dictionary<string, int> wordCount
            = new Dictionary<string, int>();

        // Iterating over words in the string
        foreach(Match match in matches)
        {
            string word = match.Value;

            // If this is the first occurrence of the word
            if (!wordCount.ContainsKey(word))
                wordCount[word] = 1;
            else
                // Increment counter of the word
                wordCount[word]++;
        }

        // Traverse dictionary and print all words whose
        // count is 1
        foreach(KeyValuePair<string, int> pair in wordCount)
        {
            if (pair.Value == 1)
                Console.WriteLine(pair.Key);
        }
    }

    // Driver Method
    public static void Main(string[] args)
    {
        string str = "Java is great. Grails is also great";
        PrintUniqueWords(str);
    }
}
Javascript
// JavaScript program to print unique words from a string

function printUniqueWords(str) {
    // Extracting words from string
    const pattern = /[a-zA-Z]+/g;
    const words = str.match(pattern) || [];

    // Map to store count of a word
    const wordCount = new Map();

    // Count occurrences of each word
    for (const word of words) {
        if (!wordCount.has(word)) {
            wordCount.set(word, 1);
        } else {
            wordCount.set(word, wordCount.get(word) + 1);
        }
    }

    // Print unique words
    for (const [word, count] of wordCount.entries()) {
        if (count === 1) {
            console.log(word);
        }
    }
}

// Driver code
const str = "Java is great. Grails is also great";
printUniqueWords(str);
Python3
# 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 string
import re

# Declare a dictionary 
dict = {} 

# Method to check whether the word 
# exists in dictionary or not 
def 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 code
if __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) 

Output
also
Java
Grails




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:

Java
import java.util.HashSet;
import java.util.Set;

public class UniqueWordsPrinter {
    // Function to print unique words
    static void printWords(Set<String> set) {
        // For loop for iterating
        for (String word : set) {
            System.out.println(word);
        }
    }

    // Main method to execute the code
    public static void main(String[] args) {
        // Input string
        String str = "geeks for geeks";

        // Storing string in the form of a set of words
        Set<String> wordSet = new HashSet<>();
        String[] words = str.split(" ");
        for (String word : words) {
            wordSet.add(word);
        }

        // Passing set to print words function
        printWords(wordSet);
    }
}
Javascript
// Function to print unique words
function printWords(set) {
    // Iterate through the set using for...of loop
    for (let word of set) {
        console.log(word); // Print each word
    }
}

// Main function to execute the code
function main() {
    // Input string
    let str = "geeks for geeks";

    // Storing string in the form of a set of words
    let wordSet = new Set();
    let words = str.split(" "); // Split the string into words
    for (let word of words) {
        wordSet.add(word); // Add each word to the set
    }

    // Passing set to printWords function to print unique words
    printWords(wordSet);
}

// Calling the main function to execute the code
main();
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 code
str = "geeks for geeks"

# storing string in the form of list of words
s = set(str.split(" "))

# passing list to print words function
printWords(s)

Output
geeks
for






Last Updated : 11 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads