7.12. string
s are mutable¶
You can change the letters in an string
one at a time using the
[]
operator on the left side of an assignment.
The active code below changes the first letter in greeting
to be
'J'
.
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.
This produces the output Jello, world!
.
- icd cream
- Remember that indexing begins at 0, not 1.
- icedcream
- Index 3 was a space and now it is "d".
- ice cream
- The character at index 3 should be changed to "d".
- iced
- The character at index 3 should be changed to "d", and the rest stays the same.
Q-2: What is printed by the following statements?
string fav_food = "ice cream";
fav_food[3] = "d";
cout << fav_food << endl;
- message[9] = "w";
- Since "l" is at index 9, replacing it with "w" fixes the message.
- message[10] = "w";
- Remember indexing starts at 0.
- "w" = message[9];
- In order to change a letter in a string, the
[] operator must be on the left of the assignment. - message[8] = "w";
- Remember indexing starts at 0.
Q-3: How can we fix the message to be “You’re a wizard Harry”?
string message = "You're a lizard Harry";
Put together the code below to create a function mixer
that takes in two strings and replaces every even index
of the first string by the corresponding index of the second. It returns the modified first string.
Example:
string_a = "food"
and string_b = "summer"
.
mixer(string_a ,string_b )
makes string_a
become “somd”.
Assume second string is greater than first.