Skip to main content
Contents
Search Book
Search Results:
No results.
Readability settings Prev Up Next Scratch ActiveCode Profile
title here
\(
\newcommand{\lt}{<}
\newcommand{\gt}{>}
\newcommand{\amp}{&}
\definecolor{fillinmathshade}{gray}{0.9}
\newcommand{\fillinmath}[1]{\mathchoice{\colorbox{fillinmathshade}{$\displaystyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\textstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptscriptstyle\phantom{\,#1\,}$}}}
\)
Section 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.
Listing 7.12.1. This active code changes the first letter in greeting to be 'J'.
This produces the output
Jello, world!.
Checkpoint 7.12.1 .
What is printed by the following statements?
string fav_food = "ice cream";
fav_food[3] = "d";
cout << fav_food << endl;
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.
Checkpoint 7.12.2 .
How can we fix the message to be βYouβre a wizard Harryβ?
string message = "You're a lizard Harry";
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.
Checkpoint 7.12.3 .
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.
string mixer(string s1,string s2) {
---
void mixer(string s1,string s2) { #paired
---
size_t size = s1.length();
---
size_t size = s2.length(); #paired
---
size_t i = 0;
while (i < size) {
---
size_t i = size - 1;
while (i < size) { #distractor
---
if( (i % 2) == 0) {
s1[i] = s2[i];
}
---
if( (i % 2) == 1) {
s1[i] = s2[i];
} #paired
---
i++;
---
}
---
return s1;
---
return s2; #paired
---
}
You have attempted
of
activities on this page.