Section 10.6 The Accumulator Pattern with Strings
Combining the
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.
Checkpoint 10.6.1.
You have attempted
1 of
5 activities on this page.