Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to replace all occurrences of 'cat' with 'dog' in the string.
MATLAB
str = 'The cat sat on the mat.'; newStr = strrep(str, 'cat', [1]);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put quotes around the replacement string.
Using the wrong function for replacement.
✗ Incorrect
The strrep function replaces all occurrences of the second argument with the third argument in the string.
2fill in blank
mediumComplete the code to replace all spaces with underscores in the string.
MATLAB
text = 'hello world example'; result = strrep(text, [1], '_');
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '_' as the substring to replace instead of the replacement.
Forgetting to use quotes around the space.
✗ Incorrect
To replace spaces, you specify the space character ' ' as the substring to replace.
3fill in blank
hardFix the error in the code to replace 'apple' with 'orange' in the string.
MATLAB
fruit = 'apple pie'; newFruit = strrep(fruit, 'apple', [1]);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Not using quotes around the replacement string.
Using double quotes instead of single quotes.
✗ Incorrect
The replacement string must be enclosed in single quotes to be recognized as a string.
4fill in blank
hardFill both blanks to replace 'dog' with 'cat' and 'mouse' with 'rat' in the string.
MATLAB
sentence = 'The dog chased the mouse.'; step1 = strrep(sentence, [1], 'cat'); result = strrep(step1, [2], 'rat');
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the order of replacements.
Replacing the wrong substrings.
✗ Incorrect
First replace 'dog' with 'cat', then replace 'mouse' with 'rat' using strrep.
5fill in blank
hardFill all three blanks to create a dictionary of words and their lengths, but only include words longer than 3 letters.
MATLAB
words = {'cat', 'elephant', 'dog', 'mouse'};
lengths = containers.Map();
for i = 1:length(words)
word = words{i};
if length(word) [1] 3
lengths([2]) = [3];
end
end Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' in the condition.
Using the length as the key instead of the word.
✗ Incorrect
We check if the word length is greater than 3, then add the word as key and its length as value to the map.