Compose a capacity that accepts a String as a contention and prints all one of a kind words in it.
Examples:
Input : Java is great. Grails is also great Output : Java Grails also
Approach:
The thought is to utilize guide to monitor words previously happened. On the whole, we need to remove all words from a String, as a string may contain a large number with accentuation marks.
For separating words from a String, allude Extracting each word from a String.
// 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 s = hm.keySet(); Iterator 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); } }
Output:
Java Grails also
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.