Skip to content

Instantly share code, notes, and snippets.

@drem-darios
Last active June 23, 2020 05:01
Show Gist options
  • Save drem-darios/7986988ed4d35df5e4a82447f3115d8a to your computer and use it in GitHub Desktop.
Save drem-darios/7986988ed4d35df5e4a82447f3115d8a to your computer and use it in GitHub Desktop.
Totals the unique words found
import java.io.*;
import java.util.*;
/*
* Given the input string, count the number of unique words found
*/
public class WordCount {
private static final String letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'-";
private static String input1 = "After beating the eggs, Dana read the next step:";
private static String input2 = "Add milk and eggs, then add flour and sugar.";
private static String input3 = "We came, we saw, we conquered...then we ate Bill's (Mille-Feuille) cake.";
public static void main(String[] args) {
System.out.println("RUN 1 **********************");
System.out.println("Unique words: " + countWords(input1).size());
System.out.println("RUN 2 **********************");
System.out.println("Unique words: " + countWords(input2).size());
System.out.println("RUN 3 **********************");
System.out.println("Unique words: " + countWords(input3).size());
}
private static Map<String, Integer> countWords(String input) {
Map<String, Integer> foundWords = new HashMap<>();
StringBuilder word = new StringBuilder();
for(int i = 0; i < input.length(); i++) {
if (isLetter(input.charAt(i))) {
word.append(input.charAt(i));
} else {
// Not a word if first char isn't a letter
if(word.toString().equals("")){
continue;
}
if (foundWords.get(word.toString()) == null) {
foundWords.put(word.toString(), 0);
}
int count = foundWords.get(word.toString()) + 1;
foundWords.put(word.toString(), count);
System.out.println("Word: " + word.toString() + " found " + count + " times!");
word = new StringBuilder();
}
}
return foundWords;
}
private static boolean isLetter(char character) {
return letters.contains(""+character);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment