7.12. strings 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'.

String are mutable
 1#include <cstddef>
 2#include <iostream>
 3#include <string>
 4
 5using std::size_t;
 6
 7int main() {
 8    std::string greeting = "Hello, world!";
 9    std::cout << greeting << '\n';
10    std::cout << "First letter: " << greeting[0] << '\n';
11    greeting[0] = 'J';
12    std::cout << greeting << '\n';
13}

Notice we are using the same operator ([]) to either get a single character from a string or to modify a single character in the string.

Q1

What is printed by the following statements?

string fav_food = "ice cream";
fav_food[3] = 'd';
cout << fav_food << '\n';

Q2

How can we fix the message to be "You're a wizard Harry"?

string message = "You're a lizard Harry";

Q3

Construct mixer, which returns a copy of s1 with each even-indexed character replaced by the corresponding character from s2. For example, mixer("food", "summer") returns "somd". Assume s2 has at least as many characters as s1.

  1.    ++i;
    }
  2. if (i % 2 != 0) {
       s1[i] = s2[i];
    }
  3. if (i % 2 == 0) {
       s1[i] = s2[i];
    }
  4. return s1;
  5. return s2;
  6. std::size_t i = 0;
  7. string mixer(string s1, string s2) {
  8. void mixer(string s1, string s2) { #distractor
  9. while (i < s1.size()) {
  10. while (i < s2.size()) {
  11. }