Challenge - 5 Problems
String Replacement Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this string replacement code?
Consider the following MATLAB code that replaces a substring in a string. What will be the output?
MATLAB
str = 'I love apples'; newStr = strrep(str, 'apples', 'oranges'); disp(newStr);
Attempts:
2 left
💡 Hint
The function strrep replaces all occurrences of the old substring with the new substring.
✗ Incorrect
The strrep function replaces 'apples' with 'oranges' in the original string, so the output is 'I love oranges'.
❓ Predict Output
intermediate2:00remaining
What does this code output after replacing multiple substrings?
This MATLAB code replaces multiple substrings sequentially. What is the final output?
MATLAB
str = 'cat bat rat'; str = strrep(str, 'bat', 'dog'); str = strrep(str, 'rat', 'fox'); disp(str);
Attempts:
2 left
💡 Hint
Each strrep call replaces all occurrences of the target substring.
✗ Incorrect
First 'bat' is replaced by 'dog', then 'rat' is replaced by 'fox', resulting in 'cat dog fox'.
❓ Predict Output
advanced2:00remaining
What is the output of this code using regexprep for string replacement?
This MATLAB code uses regexprep to replace all digits with '#'. What is the output?
MATLAB
str = 'Room 123, Floor 4'; newStr = regexprep(str, '\\d', '#'); disp(newStr);
Attempts:
2 left
💡 Hint
The pattern '\d' matches each digit individually.
✗ Incorrect
regexprep replaces each digit with '#', so '123' becomes '###' and '4' becomes '#'.
❓ Predict Output
advanced2:00remaining
What error does this code produce when using strrep incorrectly?
What error will this MATLAB code produce?
MATLAB
str = 'hello world'; newStr = strrep(str, 'world'); disp(newStr);
Attempts:
2 left
💡 Hint
Check the number of arguments strrep requires.
✗ Incorrect
strrep requires three arguments: the original string, the substring to replace, and the replacement substring. Missing the third argument causes an error.
🧠 Conceptual
expert2:00remaining
How many replacements occur in this code using strrep with overlapping substrings?
Given the code below, how many replacements does strrep perform?
MATLAB
str = 'aaaa'; newStr = strrep(str, 'aa', 'b'); disp(newStr);
Attempts:
2 left
💡 Hint
strrep does not replace overlapping occurrences twice.
✗ Incorrect
strrep replaces non-overlapping occurrences from left to right. 'aaaa' has two non-overlapping 'aa' substrings: positions 1-2 and 3-4, so 2 replacements occur.