Created
February 23, 2018 13:11
-
-
Save FedericoPonzi/1819ea3ad820f0437d326506576d84cc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.StringTokenizer; | |
import java.util.TreeMap; | |
class FrequenzeDiParoleInUnaStringa | |
{ | |
private String stringa; //La stringa da analizzare | |
private TreeMap<String, Integer> dictionary = new TreeMap<String, Integer>(); //Inizializzo il TreeMap | |
FrequenzeDiParoleInUnaStringa(String stringa) | |
{ | |
this.stringa = stringa; | |
} | |
public String frequenza() //Il metodo per il calcolo della frequenza | |
{ | |
StringTokenizer st = new StringTokenizer(stringa); //Tokenizzo la stringa | |
while(st.hasMoreTokens()) //Continua finchè ci sono token. Se non specifico il token, prende automaticamente lo spazio. | |
{ | |
String token = st.nextToken(); //Mi salvo il token | |
if(dictionary.containsKey(token)) //Se lo ho già aggiunto | |
{ | |
dictionary.put(token, dictionary.get(token)+1); //Aggiungo +1 | |
} | |
else | |
{ | |
dictionary.put(token , 1); //Altrimenti non l'ho mai incontrato quindi lo salvo e inizializzo ad 1. | |
} | |
} | |
return dictionary.toString(); //Mi stampo il dizionario usando il metodo toString | |
} | |
public static void main (String[] args) | |
{ | |
System.out.println(new FrequenzeDiParoleInUnaStringa("Ciao Ciao come come stai? Tutto bene, spero proprio proprio di si!").frequenza()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment