ContainsKey(word))
{
frequencies[word]++;
}
else
{
frequencies[word] = 1;
}
}
return frequencies;
}
...
string text = @"Do you like green eggs and ham?
I do not like them, Sam-I-am.
Listing 3.1 Using a Dictionary
to count words in text
Creates new map from
word to frequency
B
Splits text
into words C
Adds to or
updates map
D
67 Simple generics for everyday use
I do not like green eggs and ham.";
Dictionary frequencies = CountWords(text);
foreach (KeyValuePair entry in frequencies)
{
string word = entry.Key;
int frequency = entry.Value;
Console.WriteLine ("{0}: {1}", word, frequency);
}
The CountWords method B first creates an empty map from string to int. This will
effectively count how often each word is used within the given text. We then use a regular
expression C to split the text into words. It??™s crude??”we end up with two empty strings
(one at each end of the text), and I haven??™t worried about the fact that ???do??? and ???Do???
are counted separately. These issues are easily fixable, but I wanted to keep the code as
simple as possible for this example. For each word, we check whether or not it??™s already
in the map. If it is, we increment the existing count; otherwise, we give the word an initial
count of 1 D. Notice how the incrementing code doesn??™t need to do a cast to int in
order to perform the addition: the value we retrieve is known to be an int at compile
time.
Pages:
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156