hey i was working on a word count program and i need a little assistance.i cant use a string tokenizer or a set.after i get a string i need to print out the words and show how many times it was typed...like the following
"Hello there"
Hello = 1
There = 1
Now i want to know how i can separate the lines by spaces and how can i count them?
Thanx alot
02-12-2006, 01:22 PM
evlich
Once you have the strings of the words that you want, you can simply put them in a HashMap which maps strings to integers. Example code might look like this:
Code:
Map<String,Integer> freqTable = new HashMap<String,Integer>();
String word = ...;
...
Integer i = freqTable.get(word);
if( i == null ) {
freqTable.put(word, 1);
} else {
freqTable.put(word, i+1); // line requires autoboxing
}
Hope this helps.
02-14-2006, 04:36 AM
graviton
the countig given by evlich is really good. to split a sentence into words, use the split method from String class:
Code:
String text = "Hello there";
String words[] = text.split("\\s");
for (int i=0; i<words.length; i++){
System.out.println("word "+i+"="+words[i]);
}
the "\\s" in split stands for any whitespace character, eg space, return and tabs. also see javadocs to class Pattern and String.