Automation Using Selenium Webdriver
Showing posts with label how-to-find-duplicate-words-in-string. Show all posts
Showing posts with label how-to-find-duplicate-words-in-string. Show all posts

Thursday 6 April 2017

how-to-find-duplicate-words-in-string


======How To Find Duplicate Words In String==========


public class DuplicateWordsInString
{
public static void main(String[] args)
{
String test = "This sentence contains two words, one and two";
Set<String> duplicates = duplicateWords(test);
System.out.println("input : " + test);
System.out.println("output : " + duplicates);
 }
/** * Method to find duplicate words in a Sentence or String * @param input String * @return set of duplicate words */
 public static Set<String> duplicateWords(String input)
{
 if(input == null || input.isEmpty()){
return Collections.emptySet();
 }
 Set<String> duplicates = new HashSet<>();
 String[] words = input.split("\\s+");
 Set<String> set = new HashSet<>();
 for(String word : words){ if(!set.add(word))
{
duplicates.add(word);

}
 }
 return duplicates;
}
 }
Output : input : This sentence contains two words, one and two
output : [two]

how-to-find-duplicate-words-in-string