0
0
MATLABdata~10 mins

String replacement in MATLAB - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
A'dog'
B'rat'
C'bat'
D'cow'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put quotes around the replacement string.
Using the wrong function for replacement.
2fill in blank
medium

Complete 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'
A'-'
B' '
C'_'
D','
Attempts:
3 left
💡 Hint
Common Mistakes
Using '_' as the substring to replace instead of the replacement.
Forgetting to use quotes around the space.
3fill in blank
hard

Fix 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'
A'orange'
Borange
C'apple'
Dorange'
Attempts:
3 left
💡 Hint
Common Mistakes
Not using quotes around the replacement string.
Using double quotes instead of single quotes.
4fill in blank
hard

Fill 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'
A'dog'
B'cat'
C'mouse'
D'rat'
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the order of replacements.
Replacing the wrong substrings.
5fill in blank
hard

Fill 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'
A>
Bword
Clength(word)
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' in the condition.
Using the length as the key instead of the word.