9.16. Looping and CountingΒΆ
We will finish this chapter with a few more examples that show variations on the theme of iteration through the characters of a string. We will implement a few of the methods that we described earlier to show how they can be done.
The following program counts the number of times a particular letter, aChar
, appears in a
string. It is another example of the accumulator pattern that we have seen in previous chapters.
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.
The function count
takes a string as its parameter. The for
statement iterates through each character in
the string and checks to see if the character is equal to the value of aChar
. If so, the counting variable, lettercount
, is incremented by one.
When all characters have been processed, the lettercount
is returned.