Welcome back. We can also use the accumulator pattern to accumulate strings.
In this case, you start with an empty string and keep appending to it.
But when you append, you'll have to reassign to
the accumulator variable because you can't actually change the original string.
So here's an example,
a Michigan winter example where you've got someone who's got chattery teeth,
because it's so cold outside,
all of their letters are coming out double.
So they're going to say a word like
"Hello" and because their teeth are chattering it comes
out as "Helloo". So here's how we do that.
We're going to start by asking the user to type in a value that's on line one,
they enter some text and that gets assigned to the variable s. Let's suppose that,
let's make it easier for us, they say "cat",
the accumulator variable is going to have our results so far,
teeth chattering version of that string that we've accumulated so far.
Initially, there's nothing but it's going to accumulate things,
and then we start iterating one letter at a time,
the variable c is going to be bound to the letter "c",
and then we are ready to execute the accumulation part line four for the first time.
So it's going to take our current value of ac which is an empty string,
it's going to add the current value of c which is the letter "c",
and then it's going to give us a dash and the letter "c" again and another dash,
which yields a string "c-c-",
and that becomes the new value for ac.
The old string is still there but we don't worry about it anymore
because ac has been reassigned to this new string cat cat.
We're now ready to go onto the second iteration,
where we get to line four for the second time c is now bound to the letter variable "c",
c for character is now down to the letter "a",
the second letter in our string,
and we're now going to make a,
let me write it over here,
we're going to make a string that has the old value of
ac and then we append the letter a and a dash,
and a again and another dash,
and that becomes our new value.
Similarly for "t" we're going to extend
this each time that
we do all this concatenation,
we have to re-assign to a,
because we're not actually changing the own,
we have to reassign to the variable ac I should have said
and we have to do that because ac has not been changed.
So we've made a new string and we re-assign it to ac.
So, in summary, to accumulate a string,
you start with an empty string, on each iteration,
you re-assign the accumulator variable with a concatenation of
its old value and some new stuff.
At the end, you've accumulated something like" c-c-a-a-t-t.
So let's run it, I enter cat, I get c-c-a-a-t-t,
Michigan frozen winter speaking picking cat or if I run it and ask for dog,
I'll get d-d-o-o-g-g-. See you next time.