My name is Perez Perez
total words: 5
total without repeating words: 4 (since Perez appear two times)
Hope you got it, now the code:
// don't forget to add the required libraries
public void countWords(String text1 ){
// text1 is the text whose we want to get the count of words
ArrayList<String> wordArray = new ArrayList<String>();
//split the text in an array using spaces to get the words
String[] words = text1.split(" ");
//add the word to an ArrayList
wordArray.addAll(Arrays.asList(words));
//Create a HashSet
HashSet hs = new HashSet();
//next line add to the HashSet the words without repeating
hs.addAll(wordArray);
//clean the Array
wordArray.clear();
//add to the Array the words without repeating
wordArray.addAll(hs);
//print the output
System.out.
System.out.
}
No hay comentarios:
Publicar un comentario