Description
To print unique word from a string using set
Step 1: Split the string from space and store it into a array of string to
get all words.
Step 2: Store all array of string into set one by one. As set does not contain
duplicate, the output will be the unique word of string.
Example: str : this is java and java is good
output : java
and
this
is
good
C/C++
Program is Not Available in C. Please visit Java Code
Java
/* Java program to print unique word of a string using set*/
//Save it as PrintUniqueWordUsingSet.java
import java.io.*;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
public class PrintUniqueWordUsingSet {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string : ");
String str = scanner.nextLine();
str = str.trim();
System.out.println("Entered String is : " + str);
//Splitting the set by space separated
String strArray[] = str.split(" ");
//Declaring the set
Set<String> set = new HashSet<>();
//Storing the string from array into set
for(int i=0;i<strArray.length;i++) {
set.add(strArray[i]);
}
//Printing the element using iterator in java
/*Iterator itr = set.iterator();
while(itr.hasNext()){
System.out.print(itr.next()+" ");
}*/
//Printing the set element using lambda expression
set.forEach(e->{
System.out.print(e+" ");
});
}
}
Input: Enter a string : this is java and java is good Output: Entered String is : this is java and java is good java and this is good
Related Programs
1) Print All Unique Words Of A String2) Count Number of Words in a String
3) Find Occurrence Of Each Word In a Sentence
4) Program to Replace Spaces With Dots
5) Program to remove vowels from a String
6) Program to copy string
7) Find Substring of a Given String
8) Program to Reverse a String
9) Program to Compare Two Strings
10) How to find Length or Size of a String