Before you keep reading...
Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.
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.
9.14. The Accumulator Pattern with Strings¶
in operator with string concatenation using
+ and the accumulator pattern, we can
write a function that removes all the vowels from a string. The idea is to start with a string and iterate over each character, checking to see if the character is a vowel. As we process the characters, we will build up a new string consisting of only the nonvowel characters. To do this, we use the accumulator pattern.
Remember that the accumulator pattern allows us to keep a “running total”. With strings, we are not accumulating a numeric total. Instead we are accumulating characters onto a string.
Line 5 uses the
not in operator to check whether the current character is not in the string
vowels. The alternative to using this operator would be to write a very large
if statement that checks each of the individual vowel characters. Note we would need to use logical
and to be sure that the character is not any of the vowels.
if eachChar != 'a' and eachChar != 'e' and eachChar != 'i' and eachChar != 'o' and eachChar != 'u' and eachChar != 'A' and eachChar != 'E' and eachChar != 'I' and eachChar != 'O' and eachChar != 'U': sWithoutVowels = sWithoutVowels + eachChar
Look carefully at line 6 in the above program (
sWithoutVowels = sWithoutVowels + eachChar). We will do this for every character that is not a vowel. This should look
very familiar. As we were describing earlier, it is an example of the accumulator pattern, this time using a string to “accumulate” the final result.
In words it says that the new value of
sWithoutVowels will be the old value of
sWithoutVowels concatenated with
the value of
eachChar. We are building the result string character by character.
Take a close look also at the initialization of
sWithoutVowels. We start with an empty string and then begin adding
new characters to the end.
Step through the function using codelens to see the accumulator variable grow.
Check your understanding
This workspace is provided for your convenience. You can use this activecode window to try out anything you like.